Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use a variable in a regular expression?

I would like to create a String.replaceAll() method in JavaScript and I'm thinking that using a regex would be most terse way to do it. However, I can't figure out how to pass a variable in to 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 in to my regex string?

like image 355
JC Grubbs Avatar asked Jan 30 '09 00:01

JC Grubbs


People also ask

What does \\ mean in regular expression?

\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \. html?\ ' .


2 Answers

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"); 
like image 85
Eric Wendelin Avatar answered Sep 25 '22 16:09

Eric Wendelin


As Eric Wendelin mentioned, you can do something like this:

str1 = "pattern" var re = new RegExp(str1, "g"); "pattern matching .".replace(re, "regex"); 

This yields "regex matching .". However, it will fail if str1 is ".". You'd expect the result to be "pattern matching regex", replacing the period with "regex", but it'll turn out to be...

regexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregex 

This is because, although "." is a String, in the RegExp constructor it's still interpreted as a regular expression, meaning any non-line-break character, meaning every character in the string. For this purpose, the following function may be useful:

 RegExp.quote = function(str) {      return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");  }; 

Then you can do:

str1 = "." var re = new RegExp(RegExp.quote(str1), "g"); "pattern matching .".replace(re, "regex"); 

yielding "pattern matching regex".

like image 35
Gracenotes Avatar answered Sep 24 '22 16:09

Gracenotes