javascript tutorial - [Solved-5 Solutions] Variable in a regular expression - javascript - java script - javascript array



Problem:

How do you use a variable in a regular expression?

Solution 1:

Instead of using the /regex/g syntax, you can construct a new RegExp object:

var replace = "regex";
var re = new RegExp(replace,"g");
click below button to copy the code. By JavaScript tutorial team

Solution 2:

str1 = "pattern"
var re = new RegExp(str1, "g");
"pattern matching .".replace(re, "regex");
click below button to copy the code. By JavaScript tutorial team
  • This yields "regex matching ." . However, it will fail if str1 is ".". we'd expect the result to be "pattern matching regex", replacing the period with "regex", but it'll turn
  • 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");
 };
click below button to copy the code. By JavaScript tutorial team

Solution 3:

var alpha = 'fig';
'food fight'.match(alpha + 'ht')[0]; // fight
click below button to copy the code. By JavaScript tutorial team

Solution 4:

var txt=new RegExp(pattern,attributes);
click below button to copy the code. By JavaScript tutorial team

is equivalent to this:

var txt=/pattern/attributes;
click below button to copy the code. By JavaScript tutorial team

Solution 5:

String.prototype.replaceAll = function (replaceThis, withThis) {
   var re = new RegExp(replaceThis,"g"); 
   return this.replace(re, withThis);
};
var aa = "abab54..aba".replaceAll("\\.", "v");
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Variable in a regular expression