Javascript jQuery替换html页面中出现的所有字符串
我正在做一个项目,需要用另一个字符串替换所有出现的字符串。但是,我只想在字符串为文本时替换它。例如,我想把这个Javascript jQuery替换html页面中出现的所有字符串,javascript,jquery,html,replace,Javascript,Jquery,Html,Replace,我正在做一个项目,需要用另一个字符串替换所有出现的字符串。但是,我只想在字符串为文本时替换它。例如,我想把这个 <div id="container"> <h1>Hi</h1> <h2 class="Hi">Test</h2> Hi </div> 。。。但这将替换html中出现的所有“Hi”//获取给定容器中的所有文本节点 //Get all text nodes in a given container //
<div id="container">
<h1>Hi</h1>
<h2 class="Hi">Test</h2>
Hi
</div>
。。。但这将替换html中出现的所有“Hi”//获取给定容器中的所有文本节点
//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");
}
//资料来源:http://stackoverflow.com/a/4399718/560114
函数getTextNodesIn(节点,包括HiteSpaceNodes){
var textNodes=[],nonWhitespaceMatcher=/\S/;
函数getTextNodes(节点){
if(node.nodeType==3){
if(包括HiteSpaceNodes | | nonWhitespaceMatcher.test(node.nodeValue)){
textNodes.push(节点);
}
}否则{
对于(变量i=0,len=node.childNodes.length;i
请注意,这也将匹配“Hi”只是单词一部分的单词,例如“Hill”。要仅匹配整个单词,请使用/\bHi\b/g
在这里开始=>
这:
产生以下结果:
<div id="container">
<h1>Hello</h1>
<h2 class="Hi">Test</h2>
Hello
</div>
你好
试验
你好
效果不错,包括:
function str_replace_all(string, str_find, str_replace){
try{
return string.replace( new RegExp(str_find, "gi"), str_replace ) ;
} catch(ex){return string;}}
而且更容易记住
replacedstr = str.replace(/needtoreplace/gi, 'replacewith');
needtoreplace不应被
取整。
试试吧!这个问题会让你开始:如果有嵌套的HTML标记,例如,在这个特定的例子中,Test
,这是不起作用的,但是我认为OP需要一个通用的解决方案。这个例子可能是他真实HTML的精简版本。@MattBrowne你是对的,j08691的答案是正确的,虽然它实际上不是…我在那里也会做同样的评论。如果有嵌套的HTML标记,这就不起作用了,例如,Test
这是我很久以来看到的最被低估的答案之一。即使在整个
$("#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>
function str_replace_all(string, str_find, str_replace){
try{
return string.replace( new RegExp(str_find, "gi"), str_replace ) ;
} catch(ex){return string;}}
replacedstr = str.replace(/needtoreplace/gi, 'replacewith');