在JavaScript中,转换特殊字符通常涉及到两个方面:HTML实体编码和解码,以及Unicode编码和解码。
当需要将特殊字符转换为HTML实体以防止XSS攻击或确保HTML内容的正确显示时,可以使用以下方法:
示例代码:
function htmlEntities(str) {
return str.replace(/[\u00A0-\u9999<>&](?!#)/gim, function(i) {
return '&#' + i.charCodeAt(0) + ';';
});
}
console.log(htmlEntities('<div>你好, World!</div>')); // <div>你好, World!</div>
如果需要将HTML实体转换回原始字符,可以使用以下方法:
function htmlEntitiesDecode(str) {
var textarea = document.createElement('textarea');
textarea.innerHTML = str;
return textarea.value;
}
console.log(htmlEntitiesDecode('<div>你好, World!</div>')); // <div>你好, World!</div>
JavaScript中的字符串是以UTF-16编码的,但有时为了兼容性或特定需求,可能需要将字符串转换为Unicode编码。
function toUnicode(str) {
return Array.from(str).map(function(char) {
return '\\u' + char.charCodeAt(0).toString(16).padStart(4, '0');
}).join('');
}
console.log(toUnicode('你好')); // "\u4f60\u597d"
将Unicode编码转换回原始字符串:
function fromUnicode(str) {
return str.replace(/\\u[\dA-Fa-f]{4}/g, function(match) {
return String.fromCharCode(parseInt(match.replace(/\\u/, ''), 16));
});
}
console.log(fromUnicode("\u4f60\u597d")); // "你好"