Categories
JavaScript Answers

How to match string against the array of regular expressions with JavaScript?

Spread the love

Sometimes, we want to match string against the array of regular expressions with JavaScript.

In this article, we’ll look at how to match string against the array of regular expressions with JavaScript.

How to match string against the array of regular expressions with JavaScript?

To match string against the array of regular expressions with JavaScript, we use the array some method.

For instance, we write

const regexList = [/apple/, /pear/];
const text = "banana pear";
const isMatch = regexList.some((rx) => rx.test(text));

to call regexList.some with a callback that calls test on each regex to see if text matches the regex pattern.

If any regex matches text, then some returns true.

Conclusion

To match string against the array of regular expressions with JavaScript, we use the array some method.

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 *