javascript 将 unicode 字符转换为字符串格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17267329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting unicode character to string format
提问by k.ken
Does anyone know how to convert a unicode to a string in javascript. For instance:
有谁知道如何在 javascript 中将 unicode 转换为字符串。例如:
\u2211 -> ∑
\u0032 -> 2
\u222B -> ∫
\u2211 -> ∑
\u0032 -> 2
\u222B -> ∫
I basically want to be able to display the symbol in xhtml or html. Haven't decided which I will be using yet.
我基本上希望能够在 xhtml 或 html 中显示符号。还没有决定我将使用哪个。
采纳答案by k.ken
Just found a way:
String.fromCharCode(parseInt(unicode,16))
returns the right symbol representation. The unicode here doesn't have the \u
in front of it just the number.
刚刚找到了一种方法:
String.fromCharCode(parseInt(unicode,16))
返回正确的符号表示。这里的 unicode\u
前面没有数字,只有数字。
回答by Bryan Rayner
A function from k.ken's response:
来自 k.ken 响应的函数:
function unicodeToChar(text) {
return text.replace(/\u[\dA-F]{4}/gi,
function (match) {
return String.fromCharCode(parseInt(match.replace(/\u/g, ''), 16));
});
}
Takes all unicode characters in the inputted string, and converts them to the character.
获取输入字符串中的所有 unicode 字符,并将它们转换为字符。
回答by suther
To convert an given Unicode-Char like ? to String-Representation, you can also use this one-liner:
转换给定的 Unicode-Char 像 ? 到字符串表示,你也可以使用这个单行:
var unicodeToStr = '?'.codePointAt(0).toString(16)
The above example gives you 'F21D'. Used with fontAwesome, you get street-view Icon: '\F21D'
上面的例子给你'F21D'。与 fontAwesome 一起使用,你会得到街景图标:'\F21D'
回答by Amir Khorsandi
Another way:
其他方式:
const unicodeText = "F1A3";
let unicodeChar = JSON.parse(`["\u${unicodeText}"]`)[0];
回答by Pankaj Chauhan
var string = '/0004'; // One of unicode
var unicodeToStr = string.codePointAt(0).toString(16)