替换所有匹配的文本,但alt或href属性除外 [英] Replace all text matched except in alt or href attribute
问题描述
我想将所有匹配的文本替换为另一个文本,但是如果该文本位于alt
或href
属性中,则不希望替换.
示例:
I want to replace all matched text with another text, but I don't want replace if that text is in the alt
or href
attribute.
Example:
<p>Hello world!</p>
<p><img src="hello.jpg" alt="Hello"/></p>
Hello
我的代码:
var replacepattern = new RegExp('Hello', 'gi');
newcontent = newcontent.replace(replacepattern, function(match, contents, offset, s) {
var link = 'demo.com'
index++;
if (link != '') {
return '<a href="' + link + '">' + match + '</a>';
} else {
return match;
}
});
它仅适用于文本.如何匹配img src
,alt
等以外的文本?
It works perfect with text only. How can I match text except img src
, alt
etc?
推荐答案
您可以使用jQuery本身来帮助您进行替换:
You can use jQuery itself to help you with the replacement:
$(html)
.contents()
.filter(function() {
return this.nodeType == 1 || this.nodeType == 3;
}).each(function() {
this.textContent = this.textContent.replace(replacepattern, 'whatever');
});
请注意,不会替换最后一次出现的Hello
,因为将文本节点作为<body>
的子代在技术上是无效的.
Note that the last occurrence of Hello
is not replaced, because it's technically invalid to have a text node as a child of <body>
.
此外,您必须对其进行修改才能在IE< IE中工作. 9或10;基本上,浏览器应该支持node.textContent
:)
Also, you would have to modify it to work in IE < 9 or 10; basically the browser is expected to support node.textContent
:)
更新
问题稍微复杂一些;也许我的想法使它变得比以往更加困难.用jQuery替换文本节点并非易事,因此需要一些纯JS:
The problem was slightly more complicated; or maybe my mind is making it more difficult than it is. Replacing text nodes with jQuery ain't the easiest to do, so some pure JS is required for that:
$('<div><p>Hello world!</p><p><img src="hello.jpg" alt="Hello"/></p>Hello</div>')
.find('*')
.andSelf()
.each(function() {
for (var i = 0, nodes = this.childNodes, n = nodes.length; i < n; ++i) {
if (nodes[i].nodeType == 3) {
var txt = nodes[i].textContent || nodes[i].innerText,
newtxt = txt.replace(/Hello/g, 'Bye');
if (txt != newtxt) {
var txtnode = document.createTextNode(newtxt);
this.replaceChild(txtnode, nodes[i]);
}
}
}
})
.end()
.end()
.appendTo('body');
这篇关于替换所有匹配的文本,但alt或href属性除外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!