Simple javascript find and replace

后端 未结 6 1049
我在风中等你
我在风中等你 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:54

    This one works as many times as your term appears and will not kill any of the important things that shouldn't be changed (stored in the excludes array).

    usage: findAndReplace('dog','cat', document.getElementById('content'));

    /* js find andreplace Based on http://james.padolsey.com/javascript/find-and-replace-text-with-javascript/ */
    
    function findAndReplace(searchText, replacement, searchNode) {
    if (!searchText || typeof replacement === 'undefined') {
        return;
    }
    var regex = typeof searchText === 'string' ?
                new RegExp(searchText, 'g') : searchText,
        childNodes = (searchNode || document.body).childNodes,
        cnLength = childNodes.length,
        excludes = ['html','head','style','link','meta','script','object','iframe'];
    while (cnLength--) {
        var currentNode = childNodes[cnLength];
        if (currentNode.nodeType === 1 &&
          excludes.indexOf(currentNode.nodeName.toLowerCase() + ',') === -1) {
          arguments.callee(searchText, replacement, currentNode);
        }
        if (currentNode.nodeType !== 3 || !regex.test(currentNode.data) ) {
            continue;
        }
        var parent = currentNode.parentNode,
            frag = (function(){
                var html = currentNode.data.replace(regex, replacement),
                    wrap = document.createElement('div'),
                    frag = document.createDocumentFragment();
                wrap.innerHTML = html;
                while (wrap.firstChild) {
                    frag.appendChild(wrap.firstChild);
                }
                return frag;
            })();
        parent.insertBefore(frag, currentNode);
        parent.removeChild(currentNode);
    }
    }
    

提交回复
热议问题