jQuery:在 html() 中替换()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23325973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 02:14:42  来源:igfitidea点击:

jQuery: replace() in html()

jqueryhtmlreplace

提问by Martin

How can I replace html parts with replace()?

如何用 替换 html 部分replace()

<div>
    <a href="http://www.google.com">google.com</a>
</div>

JS:

JS:

var e = $("div"),
    fix = e.html().replace("google.com", "duckduckgo.com");
e.html(fix);

I guess html() is not working the same as text()?

我猜 html() 与text()?

Test: http://jsfiddle.net/Hmhrd/

测试:http: //jsfiddle.net/Hmhrd/

回答by Oriol

The problem is that .replaceonly replaces first occurence. If you want to replace all occurences, you must use a regular expression with a g(global) flag:

问题是.replace只替换第一次出现。如果要替换所有出现,则必须使用带有g(全局)标志的正则表达式:

var e = $("div"),
    fix = e.html().replace(/google\.com/g, "duckduckgo.com");
e.html(fix);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <a href="http://www.google.com">google.com</a>
</div>

Demo

演示

Remember you must escape special characterssuch as ., though. If you prefer, you can use

请记住,您必须转义诸如, 之类的特殊字符.。如果您愿意,可以使用

String.prototype.replaceAll = function(s1, s2) {
    return this.replace(
        new RegExp(  s1.replace(/[.^$*+?()[{\|]/g, '\$&'),  'g'  ),
        s2
    );
};

var e = $("div"),
    fix = e.html().replaceAll('google.com', "duckduckgo.com");
e.html(fix);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div>
    <a href="http://www.google.com">google.com</a>
</div>

Demo

演示

回答by j08691

Make your pattern global by using the gswitch:

使用g开关使您的模式全局化:

var e = $("div"),
fix = e.html().replace(/google.com/g, "duckduckgo.com");
e.html(fix);

jsFiddle example

jsFiddle 示例

This way it replaces the link andthe text.

这样它就替换了链接文本。

回答by guest271314

$("div a").attr("href", function (i, o) {
    return (/google/.test(o) ? "http://duckduckgo.com" : o)
}).html($("a", this).attr("href").substr(7))

jsfiddle http://jsfiddle.net/guest271314/6rrKs/

jsfiddle http://jsfiddle.net/guest271314/6rrKs/