How can I convert a string into a unicode character?

后端 未结 5 1978
庸人自扰
庸人自扰 2021-01-31 15:17

In Javascript \'\\uXXXX\' returns in a unicode character. But how can I get a unicode character when the XXXX part is a variable?

For example:<

5条回答
  •  生来不讨喜
    2021-01-31 15:52

    Since ES5 you can use

    String.fromCodePoint(number)

    to get unicode values bigger than 0xFFFF.

    So, in every new browser, you can write it in this way:

    var input = '2122';
    console.log(String.fromCodePoint(input));
    

    or if it is a hex number:

    var input = '2122';
    console.log(String.fromCodePoint(parseInt(input, 16)));
    

    More info:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint

提交回复
热议问题