Skip to content

Instantly share code, notes, and snippets.

@liunian
Last active March 21, 2016 09:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liunian/46192e7fe641cd9aeaea to your computer and use it in GitHub Desktop.
Save liunian/46192e7fe641cd9aeaea to your computer and use it in GitHub Desktop.
{
decodeSpecialUnicode: function(str) {
var ptn = /\\u([0-f]{4})/ig;
return str.replace(ptn, function(match, group) {
return String.fromCharCode(parseInt(group, 16));
});
},
encodeSpecialUnicode: function(str) {
// 转义特殊的 unicode 字符,如 Emoji 表情等,从而支持可能的某些情况下 api 不支持该范围 unicode 的问题
var ptn = /[^\u0000-\uD7FF\uE000-\uFFFF]/g;
return str.replace(ptn, function(m) {
return Base.toUnicode(m);
})
},
toUnicode: function(str) {
var ret = '';
for (var i = 0, l = str.length; i < l; i++) {
ret += '\\u' + ('000' + str[i].charCodeAt(0).toString(16)).substr(-4);
}
return ret;
}
}
@liunian
Copy link
Author

liunian commented Mar 21, 2016

参考 String 中的 charAtcharCodeAtcodePointAt 对宽字符的处理

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment