![](/img/trans.png)
[英]How to replace all instances of special characters in words…javascript
[英]Javascript Replace All words
我需要使用jquery和javascript替换DOM(内存中的网页)中的所有单词。 我需要对此进行转换:
<html>
<head>
Hi to all
</head>
<body>
Hi to all
</body>
</html>
变成这个:
<html>
<head>
Bye to all
</head>
<body>
Bye to all
</body>
</html>
但无需修改标签(仅包含其中的值)
一种尝试是:
jQuery.fn.replaceEachOne = function (objective, rep) {
return this.each( function(){
$(this).html( $(this).html().replace( new RegExp('(\\s'+objective+'\\s(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep) );
}
);
}
但是它会继续替换标签值,并且如果我放它会破坏页面。
救命!!!
我猜想标题中还会有其他元素,而不是仅仅用新文本替换所有内容。 试试这样的东西
$(function(){
var element = $('body, head').find('*:contains("Hi to all")');
element.html('Bye to all');
});
如果您不希望它更改标签,为什么要修改“ html”而不只是文本?
jQuery.fn.replaceEachOne = function (objective, rep) { return this.each( function(){ $(this).text( $(this).text().replace( new RegExp('(\\s'+objective+'\\s(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep) ); } ); }
一种效率低下的方法是:
var element = document.getElementsByTagName('html')[0];
element.innerHTML = element.innerHTML.replace('Hi to all', 'Bye to all');
如果需要,引号中的“ Hi to all”也可以用正则表达式代替。
最后...
谢谢大家...
jQuery.fn.replaceEachOne = function (objective, reposition) {
this.contents().each(function(){
if (this.nodeType == Node.ELEMENT_NODE) {
$(this).replaceEachOne(objective, reposition);
} else if (this.nodeType == Node.TEXT_NODE) {
var label = document.createElement("label");
label.innerHTML = this.nodeValue.replace(objective, reposition);
this.parentNode.insertBefore(label, this);
this.parentNode.removeChild(this);
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.