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?
*? The match will not throw an error, it will find all occurrences of your grouping. if you want to validate your string by a regular expression, you are probably looking forre.test(str)re.test(str)in this case... Unless you're suggesting to build a new regex that matches the given one N times (/^(\s*(\w+|"[^"]*")\s*)*$/for the example)... It seems a bit of a pain to build such regex, so I'm wondering if other solutions exist?.replace(with the regular expression, a global flag, and replace with an empty string. then if it still has length, you know you have invalid characters. If its a big string, you could build an expression for the invalid characters and test for them.const isValid = (str.match(re).length === str.split(re).filter(s => s !== '').length)