Categories
JavaScript Answers

How to convert a string to regex object with JavaScript?

Spread the love

Sometimes, we want to convert a string to regex object with JavaScript.

In this article, we’ll look at how to convert a string to regex object with JavaScript.

How to convert a string to regex object with JavaScript?

To convert a string to regex object with JavaScript, we can use the RegExp constructor.

For instance, we write:

const value = "someone@example.com";
const pattern = "^\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$"
const re = new RegExp(pattern);
const match = re.test(value);
console.log(match)

to convert the pattern string to a regex object with the RegExp constructor.

Then we can call re.test to check if value matches the re regex pattern.

Therefore, match is true since value matches the pattern, which is an email regex.

Conclusion

To convert a string to regex object with JavaScript, we can use the RegExp constructor.

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 *