-1

I'm trying to split a string based on a multiple delimiters based by referencing How split a string in jquery with multiple strings as separator but I need to include a single backslash as delimiter.

I have this

var x = 'a/b\c?d@f#g$h%i^j&k:m;n,l.o(p)q{r}t!u`v~x-y+z=A*B_C|D"E\'F G';

var separators = ['/','\\\\','\\\?','@','#','\\\$','%','\\\^','&',':',';',',','\\\.','\\\(','\\\)','{','}','!','`','~','-','\\\+','=','\\\*','_','\\\|','\\\"','\\\'',' '];
console.log(separators.join('|'));
var tokens = x.split(new RegExp(separators.join('|'), 'g'));
console.log(tokens);

And this is my result

["a", "bc", "d", "f", "g", "h", "i", "j", "k", "m", "n", "l", "o", "p", "q", "r", "t", "u", "v", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G"]

Notice that b\c is not getting split

I tried '\\\', '\\' and '\' in the separators list but nothing worked.

Thanks

lmarzetti
  • 1
  • 1
  • You probably need four, '\\\\' https://stackoverflow.com/questions/10769964/backslashes-regular-expression-javascript – Danny Ebbers Apr 02 '19 at 19:21

1 Answers1

0

As per Pushpesh Kumar Rajwanshi answer, the \ is acting as an escape char. Note below with \\ as a valid seperator now works.

See also: How to split a string with a backslash in javascript?

var x = 'a/b\\c?d@f#g$h%i^j&k:m;n,l.o(p)q{r}t!u`v~x-y+z=A*B_C|D"E\'F G';

var separators = ['/','\\\\','\\\?','@','#','\\\$','%','\\\^','&',':',';',',','\\\.','\\\(','\\\)','{','}','!','`','~','-','\\\+','=','\\\*','_','\\\|','\\\"','\\\'',' '];
console.log(separators.join('|'));
var tokens = x.split(new RegExp(separators.join('|'), 'g'));
console.log(tokens);
Bibberty
  • 4,670
  • 2
  • 8
  • 23