gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 04:19:22 24 4
gpt4 key购买 nike

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

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 - 遍历 Javascript 正则表达式匹配以修改原始字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11025264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com