Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS regexp to split string based on character not preceded by backslash

I want to use the JS String split function to split this string based only on the commas ,, and not the commas preceded by backslashes /,. How can I do this?

'this,is\,a,\,string'.split(/,/)

This code splits it on all strings, I'm not sure how to get it to split just on the commas not preceded by backslashes.

like image 668
user779159 Avatar asked Dec 06 '25 17:12

user779159


1 Answers

Since lookbehinds are not supported in JavaScript, it's hard to define "not preceded by something" pattern for split. However, you may define a "word" as a sequence of non-commas or escaped commas:

(?:\\,|[^,])+

(demo: https://regex101.com/r/d5W21v/1)

and extract all "word" matches:

var matches = "this,is\\,a,\\,string".match(/(?:\\,|[^,])+/g);
console.log(matches);
like image 184
Dmitry Egorov Avatar answered Dec 09 '25 13:12

Dmitry Egorov