How do I insert a variable into a regex pattern in JavaScript?

From Nikipedia
Jump to navigation Jump to search

To insert a variable into a regex pattern in JavaScript, you can use the RegExp constructor and pass the pattern as the first argument, followed by the flags (if any) as the second argument. The variable can be included in the pattern by using the $ symbol followed by the variable name within curly braces, like this:

const variable = 'foo'; const pattern = `\\b${variable}\\b`; const regex = new RegExp(pattern, 'g');

This will create a regular expression that matches the word 'foo' (surrounded by word boundaries \b).

You can also use template literals to define the regex pattern, like this:

const variable = 'foo'; const regex = new RegExp(`\\b${variable}\\b`, 'g'); Note that if the variable contains characters that have special meaning in regular expressions (e.g. . or *), you may need to escape them using the \ character.

You can also use the RegExp constructor to create a regex from a string pattern, like this:

const variable = 'foo'; const pattern = `\\b${variable}\\b`; const regex = new RegExp(pattern);

This will create a regular expression that matches the word 'foo' (surrounded by word boundaries \b) with no flags.

Finally, you can also use the replace method of the String object to replace a string with a variable, like this:

const variable = 'foo'; const str = 'bar'; const newStr = str.replace(/bar/g, variable);

This will replace all occurrences of the string 'bar' with the value of the variable in the str string.