JavaScript字符转Unicode,顺便说句:GitHub的Oh no页面很亮

遇到个输不出来的字符怎么办,因为输不出来的字符一般又是不常见大多数时候连名字也喊不出来的,所以想问百度谷歌大大也不大可能。如果是小白用户肯定会去把输入法软盘打开切换到其他键盘一个一个找。即使有搜狗输入法这样强大的特殊字符集的汇总,也还是要找啊。

话说那天在GitHub上折腾的时候不小心整出个错误页面(你们还是打消重现的想法吧,很难),一看好别致,我去,感叹与问号的合体,我去这是什么符号‽

啥也表说了兴许以后在自己的设计中用得上,于是就copy了下来。

后来一想哎不对啊,我不能打出来,我要使用的时候必需通过复制。这个不太保险。如果知道他的unicode代码,那就可以在HTML,JavaScript中随便使用了。

所以现在需要这么一个函数,它能把字符转为unicode码。

经查,JavaScript内建函数里有把unicode转字符的String.fromCharCode()。

刚好也有把字符转unicode转字符的String.charCodeAt()

但注意这个String.charCodeAt()直接转出来的数字为10进制的,无法在代码中像这样正常使用"uXXXX"。

所以需要调用toString(16),注意指定基数为16。

于是得到以下辅助函数:

function convert2Unicode(char) {
  return "\u" + char.charCodeAt(0).toString(16);
}

convert2Unicode("‽")->"u203D"

于是就可以这样在JS中使用了:alert("u203D");

 

进阶

进一步,可以想到除了将一个字符转为unicode表示外,稍微改造下就可以把一个字符串进行转换了。

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;
}

Reference:http://buildingonmud.blogspot.com/2009/06/convert-string-to-unicode-in-javascript.html

原文地址:https://www.cnblogs.com/Wayou/p/convert_symbol_to_unicode.html