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

Spread the love

Sometimes, we want to convert user input string to regular expression with JavaScript.

In this article, we’ll look at how to convert user input string to regular expression with JavaScript.

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

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

For instance, we write

const re = new RegExp("a|b", "i");

to create a regex with the RegExp constructor by calling it with a regex string and a string with the flags.

Therefore, re matches ‘a’ or ‘b’ in a case insensitive manner since we called RegExp the i flag.

Conclusion

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

Leave a Reply

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