Home > database >  Split Down Unescaped Character in Javascript
Split Down Unescaped Character in Javascript

Time:03-29

I have a period and backslash escaped string. I would like to split the string using any unescaped periods, but am struggling to come up with a pattern to do so.

const escaped = "two slashes: \\\\.one period: \..line and a dot: \\\.";

// ["two slashes: \\", "one period: .", "line and a dot: \."]
console.log(escaped.split(/* ? */))

enter image description here

The regex matches any . char that is immediately preceded with any amount of an even amount of backslashes (i.e. even if there are no backslashes before . at all).

With older JavaScript environment, you will need a workaround like text.match(/(?:\\[^]|[^\\.]) /g). See this regex demo. This matches any one or more sequences of a a \ and any single char or any single letter other than a backslash and a dot.

  • Related