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

前端之家收集整理的这篇文章主要介绍了通过Javascript正则表达式匹配迭代修改原始字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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"

猜你在找的JavaScript相关文章