Simple javascript find and replace

后端 未结 6 1101
我在风中等你
我在风中等你 2020-12-16 03:07

is there a straightforward method for searching within a div for a specific string and replacing it with another? I cannot use .replaceWith alone because there are other ele

6条回答
  •  余生分开走
    2020-12-16 03:36

    Just using html().replace() with match all results element attribute or tag name.

    I face this issue also, my solution is similar to findAndReplace() function from http://james.padolsey.com/javascript/find-and-replace-text-with-javascript/ but using regular expression to get all textNode and search in each of them.

    function epubSearch(query) {
        var d = document.getElementsByTagName("body")[0];
        var re = new RegExp(query, "gi");//pattern for keyword
        var re0 = new RegExp("[>][^><]*[><]", "gi");//pattern to get textnode
    
        d.innerHTML = d.innerHTML.replace(re0, function (text) {
            // with each textNode, looking for keyword
            return text.replace(re, "$&");
        });
    }
    

提交回复
热议问题