我想替换网页中的一些文本,仅替换文本,但是当我通过 document.body.innerHTML 替换时,我可能会陷入困境,如下所示:
HTML:
<p>test test </p>
<p>test2 test2</p>
<p>test3 test3</p>
Js:
var param = "test test test2 test2 test3";
var text = document.body.innerHTML;
document.body.innerHTML = text.replace(param, '*' + param + '*');
我想得到:
*test test
test2 test2
test3* test3
“期望”结果的 HTML:
<p>*test test </p>
<p>test2 test2</p>
<p>test3* test3</p>
因此,如果我想使用上面的参数(“test test test2 test2 test3”)执行此操作,则 <p></p>
不会被考虑 - 导致进入 else 部分。
如何将没有“考虑”的文本替换为可能位于其之间的 html 标记?
提前致谢。
编辑(@Sonesh Dabhi):
Basically I need to replace text in a webpage, but when I scan the webpage with the html in it the replace won't work, I need to scan and replace based on text only
编辑2:
请使用“原始”JavaScript(无 jQuery)
最佳答案
这将执行您想要的操作,它构建一个正则表达式来查找标签之间的文本并替换其中。试一试。
神奇的是
(\s*(?:<\/?\w+>)*\s*)*
在下面的代码中,有双反斜杠来在字符串中转义它们。 正则表达式本身会查找任意数量的空白字符 (\s)。内部组 (?:?\w+>)* 匹配任意数量的开始或结束标记。 ?: 告诉java脚本不计算替换字符串中的组,并且不记住它找到的匹配项。 < 是一个字面小于字符。正斜杠(开始一个结束 html 标签)需要转义,问号表示出现 0 或 1 次。这是由任意数量的空白字符进行的。
“要搜索的文本”中的每个空格都会替换为该正则表达式,使其能够匹配文本中单词之间任意数量的空格和标签,并将它们记住在编号变量 $1、$2 等中。构建替换字符串以将那些记住的变量放回原处。
匹配任意数量的标签以及它们之间的空格。
function wrapTextIn(text, character) {
if (!character) character = "*"; // default to asterik
// trim the text
text = text.replace(/(^\s+)|(\s+$)/g, "");
//split into words
var words = text.split(" ");
// return if there are no words
if (words.length == 0)
return;
// build the regex
var regex = new RegExp(text.replace(/\s+/g, "(\\s*(?:<\\/?\\w+>)*\\s*)*"), "g");
//start with wrapping character
var replace = character;
//for each word, put it and the matching "tags" in the replacement string
for (var i = 0; i < words.length; i++) {
replace += words[i];
if (i != words.length - 1 & words.length > 1)
replace += "$" + (i + 1);
}
// end with the wrapping character
replace += character;
// replace the html
document.body.innerHTML = document.body.innerHTML.replace(regex, replace);
}
关于JavaScript 用 HTML 替换文本之间的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12081500/