Sometimes, we want to match multiple words in regex with JavaScript.
In this article, we’ll look at how to match multiple words in regex with JavaScript.
How to match multiple words in regex with JavaScript?
To match multiple words in regex with JavaScript, we can use lookahead assertions.
For instance, we write:
const r = /^(?=.*foo)(?=.*bar)(?=.*baz)/
console.log('foobarbazqux'.match(r))
console.log('foobar'.match(r))
to match the substrings containing foo, bar and baz.
The strings in the regex won’t be included in the match.
Therefore, the console logs log
[""]
null
Conclusion
To match multiple words in regex with JavaScript, we can use lookahead assertions.