gpt4 book ai didi

javascript - 如何用 Javascript 实现客户端替换?

转载 作者:行者123 更新时间:2023-12-02 20:48:37 25 4
gpt4 key购买 nike

我有一个 HTML 页面,我想使用 Javascript 对其进行一些客户端替换。我想要替换的值位于一个数组中,如下所示:

var searchFor = new Object();
var replaceWith = new Object();
searchFor =
[
"quick",
"brown",
"fox",
];

replaceWith =
[
"nimble",
"black",
"cat",
];

因此,每个“棕色”实例都应替换为“黑色”。跨浏览器执行此操作的最简单方法是什么?

最佳答案

我将使用默认的 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)
}

关于javascript - 如何用 Javascript 实现客户端替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/348193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com