将文本中的汉字转换为 Unicode 表示形式。
javascript
function convertToUnicode(text) {var unicodeText = '';for (var i = 0; i < text.length; i++) {var charCode = text.charCodeAt(i);if (charCode > 127) {unicodeText += '\\u' + charCode.toString(16).toUpperCase();} else {unicodeText += text.charAt(i);}}return unicodeText;}var inputText = '这是一段测试文本。';var unicodeText = convertToUnicode(inputText);console.log(unicodeText);
还原:使用 JavaScript 的 unescape
函数,将 Unicode 转义序列还原为相应的字符。:
javascript
function convertFromUnicode(unicodeText) {var text = '';var matches = unicodeText.match(/\\u[\dA-Fa-f]{4}|./g);for (var i = 0; i < matches.length; i++) {if (matches[i].substring(0, 2) === '\\u') {text += String.fromCharCode(parseInt(matches[i].substring(2), 16));} else {text += matches[i];}}return text;}var unicodeText = '\\u8FD9\\u662F\\u4E00\\u6BB5\\u6D4B\\u8BD5\\u6587\\u672C\\u3002';var originalText = convertFromUnicode(unicodeText);console.log(originalText);