// 将字符串转换为 Unicode 编码
function stringToUnicode(str) {
let unicode = [];
for (let i = 0; i < str.length; i++) {
// 使用 charCodeAt 获取字符的 Unicode 编码,并使用 toString(16) 转换为十六进制表示
unicode.push(`\\u${str.charCodeAt(i).toString(16).padStart(4, '0')}`);
}
return unicode.join('');
}
// 将 Unicode 编码转换为字符串
function unicodeToString(unicodeStr) {
// 使用正则表达式匹配所有的 \uxxxx 格式的 Unicode 编码,并将其转换回字符
return unicodeStr.replace(/\\u([\d\w]{4})/gi, function (match, grp) {
return String.fromCharCode(parseInt(grp, 16));
});
}
// 示例
let originalString = "Hello, 世界";
let encoded = stringToUnicode(originalString);
console.log(encoded); // 输出: \u0048\u0065\u006c\u006c\u006f\u002c\u4e16\u754c
let decoded = unicodeToString(encoded);
console.log(decoded); // 输出: Hello, 世界
stringToUnicode 函数:将输入的字符串逐个字符转换为 Unicode 编码,格式为 \uxxxx
,其中 xxxx
是字符的十六进制表示。padStart(4, '0')
确保每个编码都是四位数。
unicodeToString 函数:将 Unicode 编码字符串(如 \u0048\u0065\u006c\u006c\u006f
)转换回原始字符串。通过正则表达式匹配 \uxxxx
格式的编码,并使用 String.fromCharCode
和 parseInt
将其转换回字符。
示例:展示了如何将包含中文字符的字符串进行 Unicode 编码和解码。
上一篇:js string转object
下一篇:js opencv
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站