Categories
JavaScript Answers

How to match multiple words in regex with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *