5

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

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"
4

1 回答 1

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"
于 2012-06-14T00:37:07.413 回答