我正在尝试编写一个高亮插件,并希望保留HTML格式.使用javascript进行替换时,是否可以忽略字符串中<和>之间的所有字符?
以下面的例子为例:
var string = "Lorem ipsum dolor span sit amet, consectetuer <span class='dolor'>dolor</span> adipiscing elit.";
Run Code Online (Sandbox Code Playgroud)
我希望能够实现以下目标(将'dolor'替换为'FOO'):
var string = "Lorem ipsum FOO span sit amet, consectetuer <span class='dolor'>FOO</span> adipiscing elit.";
Run Code Online (Sandbox Code Playgroud)
或者甚至可能(将'span'替换为'BAR'):
var string = "Lorem ipsum dolor BAR sit amet, consectetuer <span class='dolor'>dolor</span> adipiscing elit.";
Run Code Online (Sandbox Code Playgroud)
我非常接近tambler在这里找到答案:你可以在用jQuery替换时忽略字符串中的HTML吗?但是,出于某种原因,我无法得到公认的工作答案.
我对正则表达式完全陌生,所以任何帮助都将不胜感激.
使用浏览器的内置解析器解析HTML,innerHTML然后进行DOM遍历是实现此目的的明智方法.以下是基于这个答案的答案:
现场演示:http://jsfiddle.net/FwGuq/1/
码:
// Reusable generic function
function traverseElement(el, regex, textReplacerFunc) {
// script and style elements are left alone
if (!/^(script|style)$/.test(el.tagName)) {
var child = el.lastChild;
while (child) {
if (child.nodeType == 1) {
traverseElement(child, regex, textReplacerFunc);
} else if (child.nodeType == 3) {
textReplacerFunc(child, regex);
}
child = child.previousSibling;
}
}
}
// This function does the replacing for every matched piece of text
// and can be customized to do what you like
function textReplacerFunc(textNode, regex, text) {
textNode.data = textNode.data.replace(regex, "FOO");
}
// The main function
function replaceWords(html, words) {
var container = document.createElement("div");
container.innerHTML = html;
// Replace the words one at a time to ensure each one gets matched
for (var i = 0, len = words.length; i < len; ++i) {
traverseElement(container, new RegExp(words[i], "g"), textReplacerFunc);
}
return container.innerHTML;
}
var html = "Lorem ipsum dolor span sit amet, consectetuer <span class='dolor'>dolor</span> adipiscing elit.";
alert( replaceWords(html, ["dolor"]) );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2586 次 |
| 最近记录: |