Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of capturing group in .split() function

I have a string and i want to split it into array using the '|' character but not '\|':

var a = 'abc\&|\|cba';
var b = a.split(/([^\\])\|/);

result :

b = ["abc", "&", "|cba"]

expected output :

b = ["abc\&", "\|cba"]

Basically I cannot use capturing groups in .split() function properly.

like image 957
kingshuk basak Avatar asked Mar 03 '26 03:03

kingshuk basak


1 Answers

You could use a positive lookahead for splitting.

With escaped backslash

var a = 'abc\\&|\\|cba';
var b = a.split(/\|(?=\\)/);
console.log(b);

Without escaped backslash

/\|(?=\|)/

  • \| matches the character | literally

  • (?=\|) Positive Lookahead - Assert that the regex below can be matched

    • \| matches the character | literally

Basically it looks for a pipe, and splits if another pipe is following.

var a = 'abc\&|\|cba';
var b = a.split(/\|(?=\|)/);
console.log(b);
like image 129
Nina Scholz Avatar answered Mar 05 '26 17:03

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!