snippetjavascriptCritical
How do you use a variable in a regular expression?
Viewed 0 times
youhowusevariableregularexpression
Problem
I would like to create a
But I want to do something like this:
But obviously, this will only replace the text
String.replaceAll() method in JavaScript and think using a regex would be the most terse way to do it. However, I can't figure out how to pass a variable into a regex. I can do this already which will replace all the instances of "B" with "A"."ABABAB".replace(/B/g, "A");But I want to do something like this:
String.prototype.replaceAll = function(replaceThis, withThis) {
this.replace(/replaceThis/g, withThis);
};But obviously, this will only replace the text
"replaceThis"...so how do I pass this variable into my regex string?Solution
Instead of using the
You can dynamically create regex objects this way. Then you will do:
For older browser or node
/\sREGEX\s/g syntax, you can construct a new RegExp object:// variable == 'REGEX'
let re = new RegExp(String.raw\s${variable}\s, "g");
You can dynamically create regex objects this way. Then you will do:
"mystring1".replace(re, "newstring");For older browser or node
// variable == 'REGEX'
var re = new RegExp("\\s" + variable + "\\s", "g");
"mystring1".replace(re, "newstring");Code Snippets
"mystring1".replace(re, "newstring");// variable == 'REGEX'
var re = new RegExp("\\s" + variable + "\\s", "g");
"mystring1".replace(re, "newstring");Context
Stack Overflow Q#494035, score: 2442
Revisions (0)
No revisions yet.