[Solved] How make a conditional split in Javascript?


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 > , lgt; B , lgt; C > ; 100, 119, 150"
    .replace(/>/g, "\u200B")
    .replace(/</g, "\u200C")
    .split(";");
arr.forEach(function(el, i) {
    arr[i] = el.replace(/\u200B/g, ">").replace(/\u200C/g, "<");
});
console.log(arr); //outputs ["A > , lgt", " B , lgt", " C > ", " 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.

5

solved How make a conditional split in Javascript?