Javascript:如何替换多个相同的单词?

时间:2013-11-14 07:21:20

标签: javascript

我想知道如何用另一个字符串替换多个相同的单词。

离。

"abc I abc was abc going abc to abc bed."

"* I * was * going * to * bed."

(这是'abc'将更改为'*'的示例)

我尝试了replace("abc", "*");,但我注意到这只会更改字符串中显示的第一个abc令牌,并保留所有其他令牌。

有什么想法吗?

6 个答案:

答案 0 :(得分:3)

使用标志“g”:

string.replace(/abc/g, '*')

答案 1 :(得分:3)

您希望在字符串中执行全局替换。

为此,在JavaScript中,您需要:

  1. 将正则表达式(RegEx)作为搜索值(第一个参数)传递给replace方法
  2. 启用全局修饰符,以便通过搜索字符串全局搜索RegEx。
  3. 根据您的要求:

    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"),"*"));

Try This

答案 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, "*"));

试一试。