Simple JavaScript search and replace

Is there a simple method to search in a div for a particular string and replace it with another? I can not use .replaceWith alone because there are other elements in the div that I need to save. I tried various javascript methods found to no avail.

So something like:

$('#foo').find('this string').replaceWith('this other string');

for

<div id="foo"><div id="child">Other Element</div>this string</div>

Thank.

+5
source share
6 answers

Try the following:

var foo = $('#foo').html();

foo = foo.replace('this string', 'this other string');

$('#foo').html(foo);

Fiddle: http://jsfiddle.net/maniator/w9GzF/

+6
source

This replaces all occurrences:

var $foo = $('#foo'),
    fooHtml = $foo.html();

$foo.html(fooHtml.replace(/this string/g, 'this other string'));
+8
source

html(), () .

, findAndReplace() http://james.padolsey.com/javascript/find-and-replace-text-with-javascript/, .

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, "<span class=\"search-result\" style=\"background-color:red;\">$&</span>");
    });
}
+3

jQuery, , safeReplace .

(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);

:

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

FF 4, HTML - .

, !

+2

String.replace();?

.

$("#div").html($("#div").html().replace("search string", "replace string"));

:

var $divElement = $("#div");         //Find the div to perform replace on
var divContent = $divElement.html(); //Get the div content
divContent = divContent.replace("search string", "replace string"); //Perform replace
$divElement.html(divContent);        //Replace contents of div element.
+1
source

This works as many times as appears in your term and will not kill any important things that should not be changed (stored in an exception array).

using: 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);
}
}
0
source

All Articles