JavaScript Create Regex From String Variable

JavaScript Create Regex From String Variable

How to use variables inside regular expressions
Ferenc Almasi β€’ 2022 April 22 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

To create a regex from string variables in JavaScript, we can use a new RegExp object to pass a variable as a regex pattern:

Copied to clipboard!
const string = '[A-Z]'
const regex = new RegExp(string, 'g')

'Hello World'.replace(regex, '_')

The RegExp object takes in the regular expression as the first argument, while for the second argument, we can pass flags to be used with the expression, such as:

  • g: for matching patterns globally (match pattern multiple times)
  • i: for case insensitive matching
  • m: for matching multiple lines
  • u: for unicode support

In the above code example, we have used g to match both the letter "H" and the letter "W". If we were to omit the global flag, only the first uppercase letter would be matched.

Using variables, we could also combine multiple variables using string interpolation to get a more dynamic behavior, for example:

Copied to clipboard! Playground
const startLetter = 'A'
const endLetter = 'H'
const regex = new RegExp(`[${startLetter}-${endLetter}]`, 'g')

'Hello World'.replace(regex, 'J')

In this example, only the letter "H" will be replaced, as we essentially created a regular expression that spans from "A" to "H" ([A-H]). We could also use an array of strings to create more elaborate expressions, such as a dynamic regular expression pattern for a blacklist:

Copied to clipboard! Playground
const blacklist = [
    'suspicious-domain',
    'untrusty-site',
    'devious-page'
]

const regex = new RegExp(blacklist.join('|'), 'gi')
const isBlacklisted = regex.test(document.location.href)

Here we join the array of strings together using a pipe, which will result in the following expression that can be used to match multiple strings:

  suspicious-domain|untrusty-site|devious-page

This can be easily expanded by simply adding new strings to an array to match against more patterns. Notice that you can pass multiple flags to the RegExp object. Here, both the global and case insensitive flags were passed.

Would you like to learn more about how regular expressions work in JavaScript? Make sure to check out the tutorial below which goes into more details.

Understanding Regular Expressions in JavaScript
  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.