Divide into all monkeys with a comma

I have a javascript string containing semicolons (some of them are escaped).

My problem is how to split this line on all captive semicolons and leave escape files

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

This should work out:

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

I just found php regex that doesn't work in javascript :(

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

any ideas how to do this?

+4
source share
2 answers

JavaScript has no negative appearance (which would make this problem simple), so we can emulate it by changing the line and using a negative appearance!

 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"] 
+8
source

The following validated JavaScript function does the trick:

Seasonal semicolons:

 function splitByUnescapedSemicolons(text) { var a = []; // Array to receive results. if (text === '') return a; // Special empty string case. // Push first (possibly last) value. text = text.replace(/^[^;\\]*(?:\\[\S\s][^;\\]*)*(?=;|$)/, function(m0){a.push(m0); return '';}); // Push any 2nd, 3rd, remaining values. text = text.replace(/;([^;\\]*(?:\\[\S\s][^;\\]*)*)/g, function(m0, m1){a.push(m1); return '';}); return a; } 

This solution correctly processes escape semicolons (and avoids anything else, including escape-escape files).

Sample data:

 "" == []; ";" == ['', '']; "\;" == ['\;']; "\\;" == ['\\', '']; "one;two" == ['one', 'two']; "abc;def;ghi\;jk" == ['abc', 'def', 'ghi\;jk']; "abc;def;ghi\\;jk" == ['abc', 'def', 'ghi\\', 'jk']; 
+2
source

Source: https://habr.com/ru/post/1440099/


All Articles