Categories
JavaScript Answers

How to convert user input string to regular expression with JavaScript?

Spread the love

To convert user input string to regular expression with JavaScript, we use the RegExp constructor.

For instance, we write

const re = new RegExp("\\w+");
const matches = re.test("hello");

to call the RegExp constructor with the string with the pattern we want to match.

'\\w+' matches words.

Then we call re.test with the word we want to check if it matches.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.