我想知道如何用另一个字符串替换多个相同的单词。
离。
"abc I abc was abc going abc to abc bed."
到
"* I * was * going * to * bed."
(这是'abc'将更改为'*'的示例)
我尝试了replace("abc", "*");
,但我注意到这只会更改字符串中显示的第一个abc
令牌,并保留所有其他令牌。
有什么想法吗?
答案 0 :(得分:3)
使用标志“g”:
string.replace(/abc/g, '*')
答案 1 :(得分:3)
您希望在字符串中执行全局替换。
为此,在JavaScript中,您需要:
replace
方法根据您的要求:
var str= "abc I abc was abc going abc to abc bed.";
var newStr = str.replace(/abc/g, "*"); //newStr = "* I * was * going * to * bed."
答案 2 :(得分:1)
您需要/ g修饰符:str.replace(/abc/g, "*")
答案 3 :(得分:1)
试试这个:
var myString = "abc I abc was abc going abc to abc bed.";
var modifiedString = "";
modifiedString = myString.replace(/abc/g, '*');
alert(modifiedString);
也尝试这个:
myString .replace(new RegExp("abc","g"),"*"));
答案 4 :(得分:1)
var str= "abc I abc was abc going abc to abc bed.";
str = str.replace(/abc/g,"*");
答案 5 :(得分:1)
您需要使用RegExp:
var str = "abc I abc was abc going abc to abc bed.";
console.log(str.replace(/abc/g, "*"));
试一试。