[javascript] Javascript Regex: How to put a variable inside a regular expression?

So for example:

function(input){
    var testVar = input;
    string = ...
    string.replace(/ReGeX + testVar + ReGeX/, "replacement")
}

But this is of course not working :) Is there any way to do this?

This question is related to javascript regex variables

The answer is


Here's an pretty useless function that return values wrapped by specific characters. :)

jsfiddle: https://jsfiddle.net/squadjot/43agwo6x/

function getValsWrappedIn(str,c1,c2){
    var rg = new RegExp("(?<=\\"+c1+")(.*?)(?=\\"+c2+")","g"); 
    return str.match(rg);
    }

var exampleStr = "Something (5) or some time (19) or maybe a (thingy)";
var results =  getValsWrappedIn(exampleStr,"(",")")

// Will return array ["5","19","thingy"]
console.log(results)

To build a regular expression from a variable in JavaScript, you'll need to use the RegExp constructor with a string parameter.

function reg(input) {
    var flags;
    //could be any combination of 'g', 'i', and 'm'
    flags = 'g';
    return new RegExp('ReGeX' + input + 'ReGeX', flags);
}

of course, this is a very naive example. It assumes that input is has been properly escaped for a regular expression. If you're dealing with user-input, or simply want to make it more convenient to match special characters, you'll need to escape special characters:

function regexEscape(str) {
    return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
}

function reg(input) {
    var flags;
    //could be any combination of 'g', 'i', and 'm'
    flags = 'g';
    input = regexEscape(input);
    return new RegExp('ReGeX' + input + 'ReGeX', flags);
}

if you're using es6 template literals are an option...

string.replace(new RegExp(`ReGeX${testVar}ReGeX`), "replacement")

You can always give regular expression as string, i.e. "ReGeX" + testVar + "ReGeX". You'll possibly have to escape some characters inside your string (e.g., double quote), but for most cases it's equivalent.

You can also use RegExp constructor to pass flags in (see the docs).


It's only necessary to prepare the string variable first and then convert it to the RegEx.

for example:

You want to add minLength and MaxLength with the variable to RegEx:

function getRegEx() {
    const minLength = "5"; // for exapmle: min is 5
    const maxLength = "12"; // for exapmle: man is 12

    var regEx = "^.{" + minLength + ","+ maxLength +"}$"; // first we make a String variable of our RegEx
    regEx = new RegExp(regEx, "g"); // now we convert it to RegEx

    return regEx; // In the end, we return the RegEx
}

now if you change value of MaxLength or MinLength, It will change in all RegExs.

Hope to be useful. Also sorry about my English.


accepted answer doesn't work for me and doesn't follow MDN examples

see the 'Description' section in above link

I'd go with the following it's working for me:

let stringThatIsGoingToChange = 'findMe';
let flagsYouWant = 'gi' //simple string with flags
let dynamicRegExp = new RegExp(`${stringThatIsGoingToChange}`, flagsYouWant)

// that makes dynamicRegExp = /findMe/gi

You can use the RegExp object:

var regexstring = "whatever";
var regexp = new RegExp(regexstring, "gi");
var str = "whateverTest";
var str2 = str.replace(regexp, "other");
document.write(str2);

Then you can construct regexstring in any way you want.

You can read more about it here.


You can create regular expressions in JS in one of two ways:

  1. Using regular expression literal - /ab{2}/g
  2. Using the regular expression constructor - new RegExp("ab{2}", "g") .

Regular expression literals are constant, and can not be used with variables. This could be achieved using the constructor. The stracture of the RegEx constructor is

new RegExp(regularExpressionString, modifiersString)

You can embed variables as part of the regularExpressionString. For example,

var pattern="cd"
var repeats=3
new RegExp(`${pattern}{${repeats}}`, "g") 

This will match any appearance of the pattern cdcdcd.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to variables

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes?