299

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?

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Adam Halasz
  • 57,421
  • 66
  • 149
  • 213
  • 15
    Be aware that if you let the user supply this variable, it's easy for a malicious user to crash your application via catastrophic backtracking. – Tim Pietzcker Oct 27 '10 at 06:23
  • 5
    what is "ReGeX"? is it a variable name? it makes answers confusing by implying that it is a part of RegExp construction (in case a reader did not see those weird characters in the question). – Eduard Oct 17 '17 at 13:12

9 Answers9

371
const regex = new RegExp(`ReGeX${testVar}ReGeX`);
...
string.replace(regex, "replacement");

Update

Per some of the comments, it's important to note that you may want to escape the variable if there is potential for malicious content (e.g. the variable comes from user input)

ES6 Update

In 2019, this would usually be written using a template string, and the above code has been updated. The original answer was:

var regex = new RegExp("ReGeX" + testVar + "ReGeX");
...
string.replace(regex, "replacement");
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
  • 8
    Make sure to escape your string! See @zzzzBov answer – jtpereyda Oct 06 '15 at 21:18
  • This is not working in my case, can you please have a look [this jsfiddle](https://jsfiddle.net/ojvpsm6q/) and let me know if what i have to do if I want to set a country code dynamic into `regex` expression – Kirankumar Dafda Jun 10 '16 at 08:30
  • 18
    One important thing to remember is that in regular strings the \ character needs to be escaped while in the regex literal (usually) the / character needs to be escaped. So `/\w+\//i` becomes `new RegExp("\\w+/", "i")` – Ali Jan 16 '17 at 14:46
  • 7
    How about the /g? –  Mar 08 '17 at 03:27
  • did you able to run this example I run it and got errors last one string not defined, please test code before share it – Mahmoud Magdy Dec 23 '22 at 04:30
98

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.

steinar
  • 9,383
  • 1
  • 23
  • 37
  • var characterCount = parseInt(attrs.limitCharacterCount); console.log(characterCount); var specialCharactersValidation = new RegExp("/^[a-zA-Z0-9]{"+characterCount+"}$/"); /\/^[a-zA-Z0-9]{7}$\// requestShipmentDirectives.js:76 false main.js:46 Uncaught TypeError: Cannot read property 'offsetWidth' of null This is what is happening when I make the RegEx Dynamic. – Ankit Tanna May 08 '15 at 09:19
48

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);
}
Community
  • 1
  • 1
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • The only way this worked for me was if I deleted `ReGeX` text. So I used: `return new RegExp(input, flags);` – Michael Rader Dec 30 '16 at 01:47
  • 2
    @MichaelRader, yes, the "ReGeX" text was part of the question and used as an example, not as something that's required to make the code work. – zzzzBov Dec 30 '16 at 03:49
  • 2
    lol just realized that was just your placeholder, but as a noob this took me awhile to figure out. Thanks. – Michael Rader Dec 30 '16 at 04:43
  • I understand why string needs to be escaped. But why '\\$&' is used as a replacement – Sherin Binu Jan 28 '19 at 06:41
  • 2
    ``\\`` represents a single ``\`` character, [`$&` is the matched substring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter). – zzzzBov Jan 28 '19 at 12:53
9

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.

Ben Carp
  • 24,214
  • 9
  • 60
  • 72
7

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

string.replace(new RegExp(`ReGeX${testVar}ReGeX`), "replacement")
shunryu111
  • 5,895
  • 4
  • 27
  • 16
  • it doesn't work with template literals. I'm using regexp to validate password in my app, and I wanted to parametrize max and min length in my regular expression string and it doesn't work. ``` const newRegExp = new RegExp(`^[^\s]{${4},${32}}$`); export const validatePassword = value => value.match(newRegExp); ``` – p7adams Aug 30 '19 at 06:15
6

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).

Nikita Rybak
  • 67,365
  • 22
  • 157
  • 181
3

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.

Abbas Habibnejad
  • 433
  • 5
  • 14
2

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)
Jakob Sternberg
  • 1,758
  • 14
  • 12
2

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
  • 1
    It still works. The issue is that 'ReGeX' + testVar +' ReGeX' makes the solution confusing. Adding an actually example would clear things up in my opinion. var testVar = '321'; var regex = new RegExp( "[" + testVar + "]{2}", "g" ); // above equivalent to /[321]{2}/g – HelloWorldPeace Jun 23 '18 at 19:38