Split string by symbol that is not between specific symbols

Viewed 183

I want to split a string by "&" only in cases when "&" is not between "<%" and "%>" symbols. Between that symbols i have special expressions that i want to ignore during the split. Text is considered as special only when it is between two closest "<%" text "%>". It works like this:

<%qwr<%qrw<%tret%>wet%>qwt => only this is scpecial <%tret%>
<%test142%>wqr%>%<%%>qwr%> => only this is <%test142%> and <%%> is special

Examples:

1) my&string=21<%253&124%> <&> && => ['my', 'string=21<%253&124%> <', '> ', '', '']

2) new<%<&%235<%test&gg%>&test&f => ['new<%<', '%235<%test&gg%>', 'test', 'f']

3) a&<%&qwer&>ty%>&af => ['a', '<%&qwer&>ty%>', 'af']

I tried '\&(?![^<%]*%>)' and (?<!(<%))\&(?!(%>)) but that works wrong.

1 Answers

I would use a workaround.

  1. match all <% & %> and replace it with a special char (in my case _ underscore) so the result is <% _ %>

  2. now split the string with & char

  3. finaly replace the special char _ back to &

const mySplit = (mystr) => {
  const regex = /<%(?!%>).*%>/gm;
  const matches = mystr.match(regex);

  const tmpreplace = matches.map(e => e.replace(/&/g,'_'));
  matches.forEach(e => mystr = mystr.replace(e,tmpreplace));

  return mystr.split('&').map(e => e.replace(/_/g,'&'));
}

console.log(mySplit('my&string=21<%253&124%> <&> &&'));
console.log(mySplit('new<%<&%235<%test&gg%>&test&f'));
console.log(mySplit('a&<%&qwer&>ty%>&af'));

Related