Convert Chinese characters to Unicode encoding using JavaScript.

In JavaScript, you can convert Chinese characters to Unicode encoding using the charCodeAt() method of the String object. This method can return the Unicode encoding of a character at a specified position.

Here is an example of converting Chinese characters to Unicode encoding.

function toUnicode(str) {
  var unicodeStr = '';
  for (var i = 0; i < str.length; i++) {
    var unicode = str.charCodeAt(i).toString(16);
    unicodeStr += '\\u' + '0000'.substring(0, 4 - unicode.length) + unicode;
  }
  return unicodeStr;
}

var chineseStr = '你好,世界!';
var unicodeStr = toUnicode(chineseStr);

console.log(unicodeStr);

The output result is: Hello, world! Where \ u indicates the start of a Unicode encoding, and the following four hexadecimal numbers represent the specific Unicode encoding.

Note: To convert Unicode encoding back to Chinese characters, you can use the eval() function to parse the Unicode encoding.

var unicodeStr = '\u4f60\u597d\u3001\u4e16\u754c\uff01';
var chineseStr = eval("'" + unicodeStr + "'"); // 注意使用单引号包裹Unicode编码

console.log(chineseStr);

The output is: Hello, world!

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds