How to use dynamic variable string as regex pattern in JavaScript?

Sometimes, we want to use dynamic variable string as regex pattern in JavaScript.

In this article, we’ll look at how to use dynamic variable string as regex pattern in JavaScript.

How to use dynamic variable string as regex pattern in JavaScript?

To use dynamic variable string as regex pattern in JavaScript, we can use the RegExp constructor.

For instance, we write

const stringToGoIntoTheRegex = "abc";
const regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");

to create a regex object by calling the RegExp constructor with the "#" + stringToGoIntoTheRegex + "#" string.

The 2nd argument is the flag for the regex.

We use 'g' to make the regex return all matches of the pattern.

Conclusion

To use dynamic variable string as regex pattern in JavaScript, we can use the RegExp constructor.