2

I have this regex:

let regex = /(?=\.|[\"])/;
test = "\"test.test\""
test.split(regex)

which outputs:

[""test", ".test", """]

whereas I want

[""", "test", ".test", """]

I can't see why it splits second double quote but not first double quote

P.S.: must keep ".test" like that (and not "." "test")

user310291
  • 36,946
  • 82
  • 271
  • 487

1 Answers1

1

This is not pure regex solution but you may use this regex with a capture group and filter empty results:

const str = '"test.test"';

var arr = str.split(/(")|(?=\.)/).filter(Boolean)

console.log(arr)

Issue with your approach:

Your regex is using a lookahead assertion that can be shortened to:

(?=[."])

Which means match a zero width match that has either a dot or " at immediate next position.

Since your input has " at the start it matches position 0, then position before dot and finally position before last closing " (total 3 matches).

anubhava
  • 761,203
  • 64
  • 569
  • 643