5

The string I am trying to split:

string1, string2, string\,3, string4

I want to split the above string on each comma, except when the comma is escaped with a backslash.

I am unable to utilize negative lookbehind in my JavaScript.

My attempt:

var splits = "string1, string2, string\,3, string4".split("(?<!\\\\),");

None of the commas are being recognized.

Potential solutions: after research, I stumbled across this SO question. However, I don't understand the workarounds well enough to change the above code to the replace the use case.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
J Aronson
  • 78
  • 5

1 Answers1

5

You may use

s.match(/(?:[^,\\]|\\.)+/g)

See the regex demo. It will match 1 or more chars other than comma and backslash, or any char that is escaped with a literal backslash.

Note that the string literal should have a double backslash to define a literal backslash.

var splits = "string1, string2, string\\,3, string4".match(/(?:[^,\\]|\\.)+/g);
console.log(splits);
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563