-4

I need a split conditional to split by ;

Except IF the ; is after a &lt ou &gt. (&lt; or &gt; are converted in < or >)

Example:

Input:

A &gt; , &lt; B , &lt; C &gt; ; 100, 119, 150

Output:

A &gt;, &lt; B, &lt; C &gt;
100,119,150

I can make it:

var myString =  "A &gt; , &lt; B , &lt; C &gt; ; 100, 119, 150"
myString.replace("&gt;", "!!!before").replace("&lt;", "!!!after");    
myString.split(";");
myString.replace("!!!before", "&gt;").replace("!!!after", "&lt;");    

But this solution is a big workaround to my case, I'm searching a solution using regex or indexof to improve it.

Helio Bentzen
  • 645
  • 2
  • 12
  • 24

1 Answers1

1

One easy solution would be to use placeholders that you shouldn't otherwise expect in the given context. I've used unicode zero-width characters in the below example:

var arr = "A &gt; , lgt; B , lgt; C &gt; ; 100, 119, 150"
    .replace(/&gt;/g, "\u200B")
    .replace(/&lt;/g, "\u200C")
    .split(";");
arr.forEach(function(el, i) {
    arr[i] = el.replace(/\u200B/g, "&gt;").replace(/\u200C/g, "&lt;");
});
console.log(arr); //outputs ["A &gt; , lgt", " B , lgt", " C &gt; ", " 100, 119, 150"]

Addressing the update you added to your question: Despite regex occasionally looking shorter, it usually offers worse performance by far, see for example this article on Coding Horror.

Etheryte
  • 24,589
  • 11
  • 71
  • 116
  • no need to use placeholders, the actual < and > characters would do fine. – Touffy Apr 15 '15 at 18:56
  • @Touffy Not if you have the chars in the input string. Surely, you wouldn't expect this from something that's escaped, but the question didn't specify, there might be other operations going on before reaching this state as well. Regardless of the placeholders, this shows an easy approach of how to solve the problem. – Etheryte Apr 15 '15 at 18:58
  • @Touffy, I really cannot use < and > – Helio Bentzen Apr 15 '15 at 19:04
  • @HelioBentzen See the additional comment I appended to my answer regarding using regex. – Etheryte Apr 15 '15 at 19:05
  • 1
    @Nit, so, it's a great argument to avoid regex. Thanks! – Helio Bentzen Apr 15 '15 at 19:09