JavaScript – String Interpolation inside Regular Expressions

When you need to substitute a variable inside a regular expression you can't use the usual string interpolation in JavaScript. You have to create a RegExp object.

Let's say you have a complex regex like /^(?!.*(\w{2}).*\1)\s*(?:(?:en|de|fr|it|es)\b\s*){5}$/ and you need to dynamically manipulate the (?:en|de|fr|it|es) and the {5} parts of it.

Don't forget to escape the backslashes.

function generate_regex(array) {
  return new RegExp(

generate_regex(['en', 'de', 'fr', 'it', 'es'])


generate_regex(['en', 'de', 'fr'])


Example for String.replace()

const replace = 'regex'
const regex = new RegExp(replace, 'g')
'mystring'.replace(regex, 'newstring')