Sometimes, we want to concatenate with variable in a JavaScript regex pattern.
In this article, we’ll look at how to concatenate with variable in a JavaScript regex pattern.
How to concatenate with variable in a JavaScript regex pattern?
To concatenate with variable in a JavaScript regex pattern, we can use the RegExp
constructor to create our regex.
For instance, we write
const re = new RegExp("\\b" + test + "\\b");
to create a regex object with the RegExp
constructor.
We call it with a string with the regex pattern we want to define.
Since the argument is a string, we can concatenate values in it.
Conclusion
To concatenate with variable in a JavaScript regex pattern, we can use the RegExp
constructor to create our regex.