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(
    `^(?!.*(\\w{2}).*\\1)\\s*(?:(?:${array.join('|')})\\b\\s*){${
      array.length
    }}$`
  )
}

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

/^(?!.*(\w{2}).*\1)\s*(?:(?:en|de|fr|it|es)\b\s*){5}$/


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

/^(?!.*(\w{2}).*\1)\s*(?:(?:en|de|fr)\b\s*){3}$/

Example for String.replace()

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

Source