繁体   English   中英

jQuery替换html页面中出现的所有字符串

[英]jQuery replace all occurrences of a string in an html page

我正在开发一个项目,我需要用另一个字符串替换所有出现的字符串。 但是,我只想替换字符串,如果它是文本。 例如,我想转此......

<div id="container">
  <h1>Hi</h1>
  <h2 class="Hi">Test</h2>
  Hi
</div>

成...

<div id="container">
  <h1>Hello</h1>
  <h2 class="Hi">Test</h2>
  Hello
</div>

在该示例中,除了作为h2类的“Hi”之外,所有“Hi”被转换为“Hello”。 我试过了...

$("#container").html( $("#container").html().replace( /Hi/g, "Hello" ) )

...但是它也取代了html中出现的所有“Hi”

这个:

$("#container").contents().each(function () {
    if (this.nodeType === 3) this.nodeValue = $.trim($(this).text()).replace(/Hi/g, "Hello")
    if (this.nodeType === 1) $(this).html( $(this).html().replace(/Hi/g, "Hello") )
})

产生这个:

<div id="container">
    <h1>Hello</h1>
    <h2 class="Hi">Test</h2>
    Hello
</div>

jsFiddle例子

结果很好:

function str_replace_all(string, str_find, str_replace){
try{
    return string.replace( new RegExp(str_find, "gi"), str_replace ) ;      
} catch(ex){return string;}}

而且更容易记住......

 replacedstr = str.replace(/needtoreplace/gi, 'replacewith');

needtoreplace不应舍入'

//Get all text nodes in a given container
//Source: http://stackoverflow.com/a/4399718/560114
function getTextNodesIn(node, includeWhitespaceNodes) {
    var textNodes = [], nonWhitespaceMatcher = /\S/;

    function getTextNodes(node) {
        if (node.nodeType == 3) {
            if (includeWhitespaceNodes || nonWhitespaceMatcher.test(node.nodeValue)) {
                textNodes.push(node);
            }
        } else {
            for (var i = 0, len = node.childNodes.length; i < len; ++i) {
                getTextNodes(node.childNodes[i]);
            }
        }
    }

    getTextNodes(node);
    return textNodes;
}

var textNodes = getTextNodesIn( $("#container")[0], false );
var i = textNodes.length;
var node;
while (i--) {
    node = textNodes[i];
    node.textContent = node.textContent.replace(/Hi/g, "Hello");
}

请注意,这也将匹配单词,其中“Hi”只是单词的一部分,例如“Hill”。 要仅匹配整个单词,请使用/\\bHi\\b/g

在这里你去=> http://jsfiddle.net/c3w6X/1/

var children='';

$('#container').children().each(function(){
    $(this).html($(this).html().replace(/Hi/g,"Hello")); //change the text of the children

    children=children+$(this)[0].outerHTML; //copy the changed child
});
var theText=$('#container').clone().children().remove().end().text(); //get the text outside of the child in the root of the element

$('#container').html(''); //empty the container

$('#container').append(children+theText.replace(/Hi/g,"Hello")); //add the changed text of the root and the changed children to the already emptied element 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM