jQuery在HTML页面中替换所有字符串出现的方法

24

我正在处理一个项目,需要将所有出现的一串字符替换成另一串字符。然而,我只想替换文本字符串。比如说,我想把这个...

<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”出现次数


1
试一下!这个问题会帮助你入门:https://dev59.com/C2ox5IYBdhLWcg3wf0RP - Jeremy J Starcher
5个回答

19

这个:

$("#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示例


4
如果存在嵌套的HTML标签,例如<h2 class="Hi">Test <span class="Hi"></span></h2>,则此方法无效。 - Matt Browne

9

以下是不错的结果:

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

更易记忆...


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

需要替换的内容不应该被 ' 包围。


3
//Get all text nodes in a given container
//Source: https://dev59.com/xnVC5IYBdhLWcg3wbgdS#4399718
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

这绝对是我长时间以来看到的最被低估的答案之一。它非常适用于在整个<body>上运行。 - Xandor

0

这是你需要的 => 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 

如果存在嵌套的HTML标签,例如<h2 class="Hi">Test <span class="Hi"></span></h2>,这种方法就不起作用了。 - Matt Browne
在这个特定的例子中,但我认为OP是在寻求一个通用的解决方案。这个例子可能是他真实HTML的简化版本。 - Matt Browne
@MattBrowne 你说得对,j08691的回答就可以了。 - Amin Jafari
不,实际上不是这样的...我会在那里添加相同的评论。 - Matt Browne

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接