我有一个HTML页面,我想用Javascript进行客户端替换。我想要替换的值是这样的数组:
var searchFor = new Object();
var replaceWith = new Object();
searchFor =
[
"quick",
"brown",
"fox",
];
replaceWith =
[
"nimble",
"black",
"cat",
];
所以'brown'的每个实例都应该被'black'取代。跨浏览器的最简单方法是什么?
答案 0 :(得分:2)
我会使用默认的W3C DOM遍历递归到DOM的所有节点,只选择文本节点进行处理:
// replacer object, containing strings and their replacements
var replacer = {
"quick": "nimble",
"brown": "black",
"fox": "cat"
};
// prepare regex cache
var replacer_re = (function ()
{
var replacer_re = {};
// certain characters are special to regex, they must be escaped
var re_specials = /[][/.*+?|(){}\\\\]/g;
var word;
for (word in replacer)
{
var escaped_word = word.replace(re_specials, "\\\1");
// add \b word boundary anchors to do whole-word replacing only
replacer_re[word] = new RegExp("\\b" + escaped_word + "\\b", "g");
}
return replacer_re;
}
)();
// replace function
function ReplaceText(text)
{
var word;
for (word in replacer)
text = text.replace(replacer_re[word], replacer[word]);
return text;
}
// DOM recursing function
function ReplaceTextRecursive(element)
{
if (element.childNodes)
{
var children = element.childNodes;
for (var i = children.length - 1; i >= 0; i--)
ReplaceTextRecursive(children[i]);
}
if (element.nodeType == 3) // 3 == TEXT_NODE
element.nodeValue = ReplaceText(element.nodeValue);
}
// test it
function test()
{
ReplaceTextRecursive(document)
}