gpt4 book ai didi

javascript - 更有效地替换页面上的转义 unicode 字符?

转载 作者:行者123 更新时间:2023-11-30 17:15:39 24 4
gpt4 key购买 nike

我有一个包含转义 Unicode 字符的页面。 (例如字符汉字被转义为\u6F22\u5B57)。 This page shows how you can use the unescape() method to convert the escaped \u6F22\u5B57 to 漢字.我有一种方法可以转换所有 Unicode 转义字符,但速度不是很快。

function DecodeAllUnicodeCharacters (strID)
{
var strstr = $(strID).innerHTML;
var arrEncodeChars = strstr.match(/\\u[0-9A-Z]{4,6}/g);
for (var ii = 0; ii < arrEncodeChars.length; ii++) {
var sUnescaped = eval("unescape('"+arrEncodeChars[ii]+"')");
strstr = strstr.replace(arrEncodeChars[ii], sUnescaped);
}
$(strID).innerHTML = strstr;
}

花费时间最长的部分是在此处设置 innerHTML:$(strID).innerHTML = strstr;有没有什么好的方法可以在不重做整个页面的innerHTML的情况下替换字符?

最佳答案

设置 innerHTML 很慢的原因是因为这会导致浏览器将其解析为 HTML,如果有子元素,它们会被重新创建,这非常慢。相反,我们只需要找到 text nodes如果它们包含转义内容,则有选择地处理它们。我将以下内容基于 a previous question并展示了in a fiddle .

Element.addMethods({
// element is Prototype-extended HTMLElement
// nodeType is a Node.* constant
// callback is a function where first argument is a Node
forEachDescendant: function (element, nodeType, callback)
{
element = $(element);
if (!element) return;
var node = element.firstChild;
while (node != null) {
if (node.nodeType == nodeType) {
callback(node);
}

if(node.hasChildNodes()) {
node = node.firstChild;
}
else {
while(node.nextSibling == null && node.parentNode != element) {
node = node.parentNode;
}
node = node.nextSibling;
}
}
},
decodeUnicode: function (element)
{
var regex = /\\u([0-9A-Z]{4,6})/g;
Element.forEachDescendant(element, Node.TEXT_NODE, function(node) {
// regex.test fails faster than regex.exec for non-matching nodes
if (regex.test(node.data)) {
// only update when necessary
node.data = node.data.replace(regex, function(_, code) {
// code is hexidecimal captured from regex
return String.fromCharCode(parseInt(code, 16));
});
}
});
}
});

element.addMethods的好处| ,除了美学,就是功能模式。您可以通过多种方式使用 decodeUnicode:

// single element
$('element_id').decodeUnicode();
// or
Element.decodeUnicode('element_id');

// multiple elements
$$('p').each(Element.decodeUnicode);
// or
$$('p').invoke('decodeUnicode');

关于javascript - 更有效地替换页面上的转义 unicode 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26171152/

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