遍历 Javascript 正则表达式匹配以修改原始字符串

Iterate through Javascript regex matches to modify original string

本文关键字:修改 原始 字符串 Javascript 正则表达式 遍历      更新时间:2023-09-26

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

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"

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

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"