JSFiddle - React, Tailwind, and code Playground
HTML
<p id="id">
Some mixed \u6F22\u5B57 text
<strong>Nothing to replace here</strong>
</p>
<p><button onclick="$('id').decodeUnicode();">Decode</button></p>
JavaScript
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) {
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));
});
}
});
}
});