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

JavascriptRegexVariables

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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");

Solution 2 - Javascript

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.

Solution 3 - Javascript

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);
}

Solution 4 - Javascript

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.

Solution 5 - Javascript

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

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

Solution 6 - Javascript

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

Solution 7 - Javascript

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.

Solution 8 - Javascript

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)

Solution 9 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdam HalaszView Question on Stackoverflow
Solution 1 - JavascriptJason McCrearyView Answer on Stackoverflow
Solution 2 - JavascriptsteinarView Answer on Stackoverflow
Solution 3 - JavascriptzzzzBovView Answer on Stackoverflow
Solution 4 - JavascriptBen CarpView Answer on Stackoverflow
Solution 5 - Javascriptshunryu111View Answer on Stackoverflow
Solution 6 - JavascriptNikita RybakView Answer on Stackoverflow
Solution 7 - JavascriptAbbas HabibnejadView Answer on Stackoverflow
Solution 8 - JavascriptJakob SternbergView Answer on Stackoverflow
Solution 9 - JavascriptTimothy MitchellView Answer on Stackoverflow