簡體   English   中英

查找和替換HTML字符串。 忽略網址

[英]Find and Replace HTML Strings. Ignore URLs

我已經編寫了一個基本腳本來搜索DOM中的字符串並進行替換。 但是在當前狀態下,它也會影響鏈接的URL。

例如,將“ example”替換為“ my example”將破壞以下示例;

<a href="http://my example.com/my example">My Example</a>

我怎樣才能阻止這種情況的發生,所以結果實際上會像這樣返回?

<a href="http://example.com/example">My Example</a>

有沒有一種方法可以自動計算CAP,還是需要一個單獨的搜索字符串?

這是我的代碼;

$(document).ready(function(){

    $("body").children().each(function() {           

        $(this).html($(this).html().replace(/example/g,"my example"));

    })

});

從性能的角度來看,大約有80個單詞可以查找/替換,是否有更好的方法來處理? 缺少每種語言的單獨頁面。

如果使用.text()而不是.html(),則不會更改hrefs。

$(document).ready(function(){
    $("body").children().each(function() {           
        $(this).text($(this).text().replace(/example/g,"my example"));
    });
});

更新:我應該補充一點,這可能會導致當前所寫的意外副作用。 我建議將.replace操作限制為原子元素,如下所示:

$(document).ready(function() {
    replaceText($("body"));

    function replaceText(object) {
        var children = object.children();
        if (children.length > 0) {
            children.each(function() {
                replaceText($(this));
            });
        } else {
            object.text(object.text().replace(/example/g, "my example"));
        };
    };
});

更新:這是一種適用於自由浮動文本節點的替代方法。

$(document).ready(function() {
    replaceText($("body"));

    function replaceText(object) {

        //first we handle text nodes inside the element itself
        handleTextNodes(object); 

        //then we iterate down into the child elements 
        var children = object.children();
        children.each(function() {
            replaceText($(this));
        });
    };

    function handleTextNodes(object) {
        object.contents().filter(function() {
            return this.nodeType == 3;
        }).each(function() {
            textNodeReplace(this);
        });
    };

    function textNodeReplace(node) {
        var text = node.nodeValue;
        node.nodeValue = text.replace(/example/g, "my example");
    };
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM