Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split on all unescaped semicolons

I have a javascript-string which contains semicolons (some of them are escaped).

My problem is, how do I split this string on all unescaped semicolons and leave the escaped ones

var example = "abc;def;ghi\;jk"

This should get:

example[0] = "abc";
example[1] = "def";
example[2] = "ghi\;jk";

I only found a PHP-regex, which is not working in javascript :(

'/(?<!\\\);/'

any ideas how to do this?

like image 450
Kiuryy Avatar asked Dec 26 '22 16:12

Kiuryy


1 Answers

JavaScript has no negative look-behind (which would make this problem simple), so we can emulate it by reversing the string and using negative look-ahead!

function splitByUnescapedSemicolons(s) {
  var rev = s.split('').reverse().join('');
  return rev.split(/;(?=[^\\])/g).reverse().map(function(x) {
    return x.split('').reverse().join('');
  });
}

splitByUnescapedSemicolons("abc;def;ghi\;jk"); // => ["abc", "def", "ghi\;jk"]
like image 125
maerics Avatar answered Dec 29 '22 06:12

maerics