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 = "[email protected]";
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.