gpt4 book ai didi

javascript - 正则表达式:如果 foo 是一个词或在 URL 内,则替换它

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:03:36 25 4
gpt4 key购买 nike

鉴于此:

str = "foo myfoo http://thefoobar.com/food is awesome";
str.replace(magicalRegex, 'bar');

预期的结果是:

"bar myfoo http://thebarbar.com/bard is awesome"

我得到了 \b(foo)\b 部分,但我不知道如何从 url 中匹配和捕获 foo 。出于这些目的,假设 url 始终以 http 开头。

有什么帮助吗?

最佳答案

您可以使用此代码(适用于您的示例,但尚未尝试使用更复杂的输入):

str = 'foo myfoo http://thefoobar.com/food is awesome';
str = str.replace(/\bfoo\b/g, 'bar');
while (/http:\/\/[^\s]*?foo/.test(str))
str = str.replace(/(http:\/\/[^\s]*?)?foo/g, function($0, $1) {
return $1 ? $1 + 'bar' : $0;
});
console.log(str);

输出:

bar myfoo http://thebarbar.com/bard is awesome

现场演示:http://ideone.com/8xGy2h

关于javascript - 正则表达式:如果 foo 是一个词或在 URL 内,则替换它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15370623/

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