在 Javascript 中,如何使用’/’和’/g’内的变量对字符串执行全局替换?

我想在 Javascript 中使用 String.place 执行字符串的全局替换。

在文档中我读到我可以用/g 做到这一点,例如;

var mystring = mystring.replace(/test/g, mystring);

这将替换 mystring 中的所有匹配项。表达式中没有引号。

但是如果我要查找一个变量,没有引号怎么做到这一点呢?

我试过这样的方法:

var stringToFind = "test";

//第一次尝试

mystring = mystring.replace('/' + stringToFind + '/g', mystring);

//第二次尝试,没有多少意义

mystring = mystring.replace(/stringToFind/g, mystring);

但是没用,有什么办法吗?

102632 次浏览
var mystring = "hello world test world";
var find = "world";
var regex = new RegExp(find, "g");
alert(mystring.replace(regex, "yay")); // alerts "hello yay test yay"

In case you need this into a function

  replaceGlobally(original, searchTxt, replaceTxt) {
const regex = new RegExp(searchTxt, 'g');
return original.replace(regex, replaceTxt) ;
}

Try:

var stringToFind = "test";
mystring = mystring.replace(new RegExp(stringToFind, "g"), mystring);

Thats a regular expression, not a string. Use the constructor for a RegExp object to dynamically create a regex.

var r = new RegExp(stringToFind, 'g');
mystring.replace(r, 'some replacement text');

If you want variables interpolated, you need to use the RegExp object

https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Regular_Expressions

Example:

var str = "This is my name";
var replace = "i";
var re = new RegExp(replace, 'g')


str = str.replace(re, 'p');
alert(str);

For regex, new RegExp(stringtofind, 'g');. BUT. If ‘find’ contains characters that are special in regex, they will have their regexy meaning. So if you tried to replace the '.' in 'abc.def' with 'x', you'd get 'xxxxxxx' — whoops.

If all you want is a simple string replacement, there is no need for regular expressions! Here is the plain string replace idiom:

mystring= mystring.split(stringtofind).join(replacementstring);

Can you use prototype.js? If so you could use String.gsub, like

var myStr = "a day in a life of a thing";
var replace = "a";
var resultString = myStr.gsub(replace, "g");
// resultString will be "g day in g life of g thing"

It will also take regular expressions. To me this is one of the more elegant ways to solve it. prototypejs gsub documentation

String.prototype.replaceAll = function (replaceThis, withThis) {
var re = new RegExp(RegExp.quote(replaceThis),"g");
return this.replace(re, withThis);
};




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


var aa = "qwerr.erer".replaceAll(".","A");
alert(aa);

silmiar post

Dynamic global replace

I came to this thread looking for a slightly more complex solution which isn't answered here. I've now found the answer so I'm going to post it in case anyone else finds it useful.

I wanted to do a dynamic global replace, where the replacement strings are based on the original matches.

For example, to capitalise the first letter of all words (e.g. "cat sat mat" into "Cat Sat Mat") with a global find replace. Here's how to do that.

function capitaliseWords(aString) {
// Global match for lowercase letters following a word boundary
var letters = aString.match(/\b[a-z]/g), i, letterMatch;
// Loop over all matched letters
for( i = 0; i < letters.length; i++ ) {
// Replace the matched letters with upper case versions
letterMatch = new RegExp('\\b'+letters[i]); // EDIT - slight fix
aString = aString.replace(letterMatch, letters[i].toUpperCase());
}
// Return our newly capitalised string
return aString;
}


alert( capitaliseWords("cat sat mat") ); // Alerts "Cat Sat Mat"

Regular expressions are much slower then string search. So, creating regex with escaped search string is not an optimal way. Even looping though the string would be faster, but I suggest using built-in pre-compiled methods.

Here is a fast and clean way of doing fast global string replace:

sMyString.split(sSearch).join(sReplace);

And that's it.

You can do using following method

see this function:

function SetValue()
{
var txt1='This is a blacK table with BLack pen with bLack lady';
alert(txt1);
var txt2= txt1.replace(/black/gi,'green');
alert(txt2);
}

syntax:

/search_string/{g|gi}

where

  • g is global case-sensitive replacement
  • gi is blobal case-insensitive replacement

You can check this JSBIN link

http://jsbin.com/nohuroboxa/edit?html,js,output

You can use the following solution to perform a global replace on a string with a variable inside '/' and '/g':

myString.replace(new RegExp(strFind, 'g'), strReplace);