通过Javascript正则表达式匹配迭代修改原始字符串

时间:2012-06-14 00:32:07

标签: javascript regex

只是想知道在字符串上替换匹配的最佳方法。

value.replace("bob", "fred");

例如,工作,但我希望每个“bob”实例都替换为我存储在数组中的随机字符串。只是进行正则表达式匹配会返回匹配的文本,但不允许我在原始字符串中替换它。有一种简单的方法可以做到这一点吗?

例如,我希望字符串:

"Bob went to the market. Bob went to the fair. Bob went home"

可能弹出

"Fred went to the market. John went to the fair. Alex went home"

1 个答案:

答案 0 :(得分:4)

您可以使用函数调用的值替换:

var names = ["Fred", "John", "Alex"];
var s = "Bob went to the market. Bob went to the fair. Bob went home";
s = s.replace(/Bob/g, function(m) {
    return names[Math.floor(Math.random() * names.length)];
});

这给出了例如:

"John went to the market. Fred went to the fair. John went home"