I need to split a string. I have a regex able to match each substring entirely.
I tried using it with String.prototype.matchAll()
and it's able to split , but that function accepts "invalid tokens" too: pieces of the string that don't match my regex. For instance:
var re = /\s*(\w+|"[^"]*")\s*/g // matches a word or a quoted string
var str = 'hey ??? "a"b' // the '???' part is not a valid token
var match = str.matchAll(re)
for(var m of match){
console.log("Matched:", m[1])
}
Gives me the token hey
, "a"
and b
. Those are indeed the substrings that match my regex, but I would have wanted to get an error in this case, since string contains ???
which is not a valid substring.
How can I do this?