【问题标题】:jQuery: replace() in html()jQuery:在 html() 中替换()
【发布时间】:2014-06-13 02:34:30
【问题描述】:

如何将 html 部分替换为 replace()

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

JS:

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

我猜 html() 与 text() 的工作方式不同?

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

【问题讨论】:

    标签: jquery html replace


    【解决方案1】:

    问题是.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

    请记住,您必须转义 special characters,例如 .。如果您愿意,可以使用

    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

    【讨论】:

    • 谢谢。保存replaceAll()以防万一:)
    【解决方案2】:

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

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

    jsFiddle example

    这样它替换了链接文本。

    【讨论】:

    • 让你的正则表达式全球化,OP 根本不使用正则表达式 ;)
    • 哦! replace() 只吃正则表达式:/
    • @j08691,很抱歉打扰您,但同样,他没有使用 模式。不过不要误会我的意思
    【解决方案3】:
    $("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/

    【讨论】:

    • 不过,这不会替换链接的 href 属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 2016-08-17
    • 2012-09-13
    • 1970-01-01
    相关资源
    最近更新 更多