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.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.