我尝试将文本解析为html,进行一些更改,然后再次返回纯文本。
我要做的更改是用另一个术语(例如'old'
替换'new'
)来低音替换某个术语。
我只想更改文本类型,而不是html元素的属性和属性(例如,不应更改href
值。)。
请参阅代码:
h= '<span myAtrib="something"><a href="old(this SHOULD NOT be changed)">old(this SHOULD be changed)</a></span>';
h=$("<div>"+ h +"</div>").find('span[myAtrib="something"]').html(function (i, oldHtml) {
oldHtml = oldHtml.replace(/old/g, 'new');
return oldHtml;
}).end().html();
我应该如何仅在文本节点上进行替换,或者至少我应该如何过滤掉锚元素?
答案 0 :(得分:2)
如何仅在文本节点上进行替换
通过递归迭代所有子节点/后代并测试节点是否是文本节点:
function replace($element, from, to) {
$element.contents().each(function() {
if (this.nodeType === 3) { // text node
this.nodeValue = this.nodeValue.replace(from, to);
}
else if (this.nodeType === 1) { // element node
replace($(this), from, to);
}
});
}
var $ele = $("<div>"+ h +"</div>").find('span[myAtrib="something"]')
replace($ele, /old/g, "new");
var html = $ele.end().html();
您也可以在没有jQuery的情况下轻松完成此操作。
答案 1 :(得分:1)
另一种方法是
h = $("<div id='root'>" + h + "</div>").find('span[myAtrib="something"]').find('*').addBack().contents().each(function () {
if (this.nodeType == 3 && $.trim(this.nodeValue) != '') {
this.nodeValue = this.nodeValue.replace(/old/g, 'new')
}
}).end().end().end().end().html();
演示:Fiddle