P粉1414555122023-08-24 10:47:54
As Eric Wendelin mentioned, you can do this:
str1 = "pattern" var re = new RegExp(str1, "g"); "pattern matching .".replace(re, "regex");
This produces "Regular expression match."
. However, it fails if str1 is "."
. You expected the result to be "Pattern Matching Regular Expression"
, replacing the period with
"Regular Expression", but the result would be...
regexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregex
This is because, although "."
is a string, in the RegExp constructor it is still interpreted as a regular expression, representing any non-newline character, representing each character in the string character. For this purpose, the following functions may be useful:
RegExp.quote = function(str) { return str.replace(/([.?*+^$[\]\(){}|-])/g, "\"); };
Then you can do this:
str1 = "." var re = new RegExp(RegExp.quote(str1), "g"); "pattern matching .".replace(re, "regex");
Produces "pattern matching regular expression"
.
P粉3189281592023-08-24 10:01:04
You can construct a new RegExp object:
var replace = "regex\d"; var re = new RegExp(replace,"g");
You can dynamically create regular expression objects this way. Then you would do:
"mystring1".replace(re, "newstring");