Simple javascript find and replace

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

    Here's a jQuery plugin I just wrote that provides safeReplace for collections.

    (function($){
    
    $.fn.safeReplace = function ( find, replacement ) {
    
        return this.each(function(index, elem) {
    
            var
                queue = [elem],
                node,
                i;
    
            while (queue.length) {
    
                node = queue.shift();
    
                if (node.nodeType === 1) {
                    i = node.childNodes.length;
                    while (i--) {
                        queue[queue.length] = node.childNodes[i];
                    }
                } else if (node.nodeType === 3) {
                    node.nodeValue = node.nodeValue.replace( find, replacement );
                }
            }
    
        });
    };
    
    })(jQuery);
    

    And here's how you use it:

    $('#foo').safeReplace( /this string/g, 'something else' );
    

    I've only tested in FF 4, and only on the sample HTML input - more testing is recommended.

    Hope this helps!

提交回复
热议问题