JQuery заменяет все вхождения строки на html-странице
Я работаю над проектом, где мне нужно заменить все вхождения строки другой строкой. Тем не менее, я хочу только заменить строку, если это текст. Например, я хочу включить это...
<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>
В этом примере все "Hi" были преобразованы в "Hello", за исключением "Hi" в качестве класса h2.
Я пробовал...
$("#container").html( $("#container").html().replace( /Hi/g, "Hello" ) )
... но заменяет все вхождения "Hi" в html, а также
Ответы
Ответ 1
Это:
$("#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
Ответ 2
Хорошие результаты:
function str_replace_all(string, str_find, str_replace){
try{
return string.replace( new RegExp(str_find, "gi"), str_replace ) ;
} catch(ex){return string;}}
и легче запомнить...
Ответ 3
replacedstr = str.replace(/needtoreplace/gi, 'replacewith');
requiretoreplace не должен округляться '
Ответ 4
//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");
}
Обратите внимание, что это также будет соответствовать словам, где "Привет" является только частью слова, например. "Холм". Чтобы соответствовать только всему слову, используйте /\bHi\b/g
Ответ 5
здесь вы идете = > 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