Javascript 简单的javascript查找和替换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5983681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:45:13  来源:igfitidea点击:

Simple javascript find and replace

javascriptjqueryreplace

提问by pac

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 elements within the div I need to preserve. I've tried various javascript methods found here to no avail.

是否有一种直接的方法可以在 div 中搜索特定字符串并将其替换为另一个?我不能单独使用 .replaceWith ,因为我需要保留 div 中的其他元素。我尝试了在这里找到的各种 javascript 方法都无济于事。

So something like:

所以像:

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

for:

为了:

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

Thanks.

谢谢。

采纳答案by Naftali aka Neal

Try this:

尝试这个:

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

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

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

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

小提琴:http: //jsfiddle.net/maniator/w9GzF/

回答by Code Maverick

This replaces all occurrences:

这将替换所有出现:

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

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

回答by AnVo

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

只需使用 html().replace() 匹配所有结果元素属性或标签名称。

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.

我也面临这个问题,我的解决方案类似于http://james.padolsey.com/javascript/find-and-replace-text-with-javascript/ 中的findAndReplace() 函数,但使用正则表达式来获取所有 textNode 和搜索在他们每个人。

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>");
    });
}

回答by jimbo

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

这是我刚刚编写的一个提供safeReplace集合的 jQuery 插件。

(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.

我只在 FF 4 中测试过,并且只在示例 HTML 输入上测试过 - 建议进行更多测试。

Hope this helps!

希望这可以帮助!

回答by Karl Nicoll

What's wrong with String.replace();?

String.replace()有什么问题?

e.g.

例如

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

Or Exploded:

或爆炸:

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

回答by marblegravy

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).

这个工作与您的术语出现的次数一样多,并且不会杀死任何不应更改的重要内容(存储在 excludes 数组中)。

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

用法: 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);
}
}