How to convert Unicode to character which is displayed in web page using JavaScript?

10,287

Solution 1

If you inject a string with unicode characters via javascript into a webpage they will be displayed the way they should automatically (given that the browser innquestion support the display of that character).

This can be seen in this example: http://jsfiddle.net/KyuKE/1/

You can read the data in a textNode by accessing it's data property which will give you a string. This string will have the charCodeAt method available to get the charCode.

Example can be seen here: http://jsfiddle.net/KyuKE/2/

You can read the documentation for charCodeAt here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/charCodeAt

Solution 2

Code as following

Convert utf8 to string

let font = '\u5b8b\u4f53';
console.log('font', font); // -> font 宋体

let str = String.raw`${font}`;
console.log('str', str);  // -> str 宋体

Convert string to utf8

function toUnicode(theString) {
  var unicodeString = '';
  for (var i=0; i < theString.length; i++) {
    var theUnicode = theString.charCodeAt(i).toString(16).toUpperCase();
    while (theUnicode.length < 4) {
      theUnicode = '0' + theUnicode;
    }
    theUnicode = '\\u' + theUnicode;
    unicodeString += theUnicode;
  }
  return unicodeString;
}

toUnicode(str[0]);  // -> '\\u5B8B'

I hope it helps.

Reference:

  1. Convert a String to Unicode in Javascript | Building on Mud
Share:
10,287
weilou
Author by

weilou

Updated on June 30, 2022

Comments

  • weilou
    weilou almost 2 years

    For example:

    If I've a string which is Unicode: \u4E45

    I wanna display this character to web page using JavaScript. How can I do?

    And my second question is that if I've a Chinese character: 依

    I wanna get its Unicode (\u4F9D) using JavaScript. How can I do?

    Thank you very much!