我正在开发一个项目,我需要用另一个字符串替换所有出现的字符串。但是,我只想替换字符串,如果它是文本。例如,我想转此......
<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”
答案 0 :(得分:17)
此:
$("#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 example 强>
答案 1 :(得分: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;}}
更容易记住...
答案 2 :(得分:7)
replacedstr = str.replace(/needtoreplace/gi, 'replacewith');
needtoreplace不应舍入'
答案 3 :(得分:1)
//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");
}
请注意,这也会匹配&#34;嗨&#34;只是这个词的一部分,例如&#34;山&#34 ;.要仅匹配整个单词,请使用/\bHi\b/g
答案 4 :(得分:0)
这里你去=&gt; 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