Javascript Regex: How to put a variable inside a regular expression?
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");
Inserting variables into regular expressions
You can use a RegExp
object for that, here is an example:
var countries = ['US', 'UK', 'Canda', 'Mexico', 'Panama', 'Dominican Republic', 'Brazil', 'Germany', 'France', 'Portugal', 'Spain', 'the Netherlands'];
var userCountry = prompt("Please enter a country", "");
var beenToUserCountry = countries.some(country => new RegExp(`^${userCountry}$`, "i").test(country));
if (beenToUserCountry) { document.write(`Yes, I have been to ${userCountry}.`); } else { document.write(`No, I haven't been to ${userCountry} yet.`); }
How to use a variable inside a RegEx pattern?
Use new RegExp(string)
to build a regular expression dynamically. The literal /../
form cannot be used with dynamic content.
Make sure to have a valid pattern after building the string.
var len = 99;
var re = new RegExp(".(?=.{" + len + "})", "g");
var output = input.replace(re, "*")
Also see (and vote for dupe of):
- How do you use a variable in a regular expression?
How do you use a variable in a regular expression?
Instead of using the /regex\d/g
syntax, you can construct a new RegExp object:
var replace = "regex\\d";
var re = new RegExp(replace,"g");
You can dynamically create regex objects this way. Then you will do:
"mystring1".replace(re, "newstring");
How to use a variable within a regex in Javascript?
const regex = new RegExp(`^.*\\b(${vRegex})\\b.*$`);
You can use template literals (`
, instead of "
/'
) to build strings that you can interpolate expresions into; no more oldschool +
ing.
The only thing that was an actual issue with your code, though, was the \b
character class. This sequence is what you want RegExp
to see, but you can't just write that, otherwise you're sending RegExp
the backspace character.
You need to write \\b
, which as you can see from that link, will make a string with a \
and an ordinary b
for RegExp
to interpret.
How to put variable in regular expression match?
You need to use the RegExp
constructor instead of a regex literal.
var string = 'asdgghjjkhkh';
var string2 = 'a';
var regex = new RegExp( string2, 'g' );
string.match(regex);
If you didn't need the global modifier, then you could just pass string2
, and .match()
will create the regex for you.
string.match( string2 );
Use dynamic (variable) string as regex pattern in JavaScript
To create the regex from a string, you have to use JavaScript's RegExp
object.
If you also want to match/replace more than one time, then you must add the g
(global match) flag. Here's an example:
var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
In the general case, escape the string before using as regex:
Not every string is a valid regex, though: there are some speciall characters, like (
or [
. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:
function escapeRegExp(stringToGoIntoTheRegex) {
return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
Note: the regex in the question uses the s
modifier, which didn't exist at the time of the question, but does exist -- a s
(dotall) flag/modifier in JavaScript -- today.
JavaScript regex pattern concatenate with variable
var re = new RegExp("/\b"+test+"\b/");
\b
in a string literal is a backspace character. When putting a regex in a string literal you need one more round of escaping:
var re = new RegExp("\\b"+test+"\\b");
(You also don't need the //
in this context.)
Related Topics
Difference Between Settimeout with and Without Quotes and Parentheses
Create a Custom Callback in JavaScript
How to Parse JSON Using Node.Js
How to Get the Size of a JavaScript Object
Check If a JavaScript String Is a Url
Access Control Request Headers, Is Added to Header in Ajax Request with Jquery
Are There Constants in JavaScript
How to Automate Shadow Dom Elements Using Selenium
What Is the Stability of the Array.Sort() Method in Different Browsers
Execute Script After Specific Delay Using JavaScript
Two Sets of Parentheses After Function Call
JavaScript - Href VS Onclick for Callback Function on Hyperlink
Detect Ie Version (Prior to V9) in JavaScript
Prevent Double Submission of Forms in Jquery
Convert String with Commas to Array
How to Use Async/Await at the Top Level