Javascript 替换除alt或href属性外的所有匹配文本
我想用另一个文本替换所有匹配的文本,但如果该文本在Javascript 替换除alt或href属性外的所有匹配文本,javascript,jquery,regex,Javascript,Jquery,Regex,我想用另一个文本替换所有匹配的文本,但如果该文本在alt或href属性中,我不想替换。 例如: 你好,世界 你好 我的代码: var replacepattern = new RegExp('Hello', 'gi'); newcontent = newcontent.replace(replacepattern, function(match, contents, offset, s) { var link = 'demo.com' index++; if (link !=
alt
或href
属性中,我不想替换。
例如:
你好,世界
你好
我的代码:
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;
}
});
var replacepattern=newregexp('Hello','gi');
newcontent=newcontent.replace(replacepattern,function(match,contents,offset,s){
var link='demo.com'
索引++;
如果(链接!=''){
返回“”;
}否则{
复赛;
}
});
它只适用于文本。除了
img src
、alt
等,我如何匹配文本?您可以使用jQuery本身来帮助您进行替换:
$(html)
.contents()
.filter(function() {
return this.nodeType == 1 || this.nodeType == 3;
}).each(function() {
this.textContent = this.textContent.replace(replacepattern, 'whatever');
});
请注意,Hello
的最后一次出现没有被替换,因为将文本节点作为
的子节点在技术上是无效的
此外,您必须修改它以在IE<9或10中工作;基本上,浏览器应该支持节点。textContent
:)
更新
问题稍微复杂一些;或者我的想法让事情变得更难。用jQuery替换文本节点不是最容易的,因此需要一些纯JS:
$('<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');
$(“你好,世界!你好”)
.find(“*”)
.andSelf()
.each(函数({
对于(var i=0,nodes=this.childNodes,n=nodes.length;i
所说的“etc”。你是指任何html属性吗?你必须使用html解析器,而不是正则表达式才能真正确定我的想法。@Blazemonger是的,替换为文本,而不是attributesHey!我找到了解决办法。使用这个正则表达式:newregexp('hello(?![^'),“gi”)谢谢Jack,我试过你的代码,但是在替换之后,img标签被删除了。有什么想法吗?试着添加一个div包装器,像这样:Hello world!Hello
我想当节点不在同一级别时出现了问题。非常感谢@Jack!我通过使用这个正则表达式找到了一个解决方案:new RegExp(
但是你的方法很好。
$('<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');