jQuery: replace() in html()

前端 未结 3 853
臣服心动
臣服心动 2021-01-05 13:23

How can I replace html parts with replace()?


         


        
3条回答
  •  没有蜡笔的小新
    2021-01-05 13:36

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

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

    Demo

    Remember you must escape special characters such 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);
    
    

    Demo

提交回复
热议问题