我试图在整个HTML页面中将“坏”的字体颜色替换为红色,但有两个主要问题,首先它在替换之前重复整个句子,我不希望这样,也不是“糟糕”也被替换但我只想要替换“坏”这个词中的字体。我该怎么做?这是我的代码
window.onload = function() {
var text = document.getElementById("content");
var str = text.innerHTML,
reg = /red/ig;
var toStr = String(reg);
var color = (toStr.replace('\/g', '|')).substring(1);
var colors = color.replace("|");
if (colors.indexOf("red") > -1) {
str = str.replace(/bad/g, '<span style="color:red;">bad</span>');
}
document.getElementById("updated").innerHTML = str;
}
<div id="content">are they good or bad, tell me how badly it is if bad.</div>
<div id="updated"></div>
答案 0 :(得分:1)
使用 \ b (单词边界标记),如raphael75所述
str = str.replace(/\b(bad)\b/gi, '<span style="color:red;">$1</span>');
我也是:
var str = "bad incredibad badly Bad, testing bad, bad. bad";
str = str.replace(/\b(bad)\b/gi, '<span style="color:red;">$1</span>');
document.getElementsByTagName('p')[0].innerHTML = str;
<p></p>
regex101是JavaScript RegEx的首选地点
答案 1 :(得分:0)
要替换HTML文档中的文本,最好遍历DOM树并替换所需的文本节点内容。
要仅匹配完整字词(“不良”但不“严重”),请将正则表达式与word boundary anchors \b
一起使用。
以下实现执行深度优先的DOM树遍历,并将包含单词“bad”的文本节点替换为该单词之前和之后的文本的文本节点,并替换<span style="color: red">bad</span>
代替“bad” :
var walk = (node, func) => {
var children = node.childNodes;
for (var i = children.length - 1; i >= 0; --i) {
walk(children[i], func);
}
func(node);
};
var highlight = (text, color) => {
var span = document.createElement("span");
span.style.color = color;
span.appendChild(document.createTextNode(text));
return span;
};
var root = document.getElementById("content");
walk(root, (node) => {
if (node.nodeType != Node.TEXT_NODE) return;
var texts = node.data.split(/\bbad\b/),
length = texts.length;
if (length > 1) {
var fragment = texts.reduce((fragment, text, i) => {
fragment.appendChild(document.createTextNode(text));
if (i < length - 1) fragment.appendChild(highlight("bad", "red"));
return fragment;
}, document.createDocumentFragment());
node.parentNode.replaceChild(fragment, node);
}
});
<div id="content">are they good or bad, tell me how badly it is <bad>bad bad bad</bad> if bad.</div>