Skip to content

Instantly share code, notes, and snippets.

@liunian
Last active June 28, 2017 06:50
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/552143668ec836350b93 to your computer and use it in GitHub Desktop.
Save liunian/552143668ec836350b93 to your computer and use it in GitHub Desktop.
把超出 ascii 范围的字符(如中文)等转为基于 ascii 范围字符的转义表达形式(https://github.com/mishoo/UglifyJS2/blob/master/lib/output.js#L76
// from https://github.com/mishoo/UglifyJS2/blob/harmony/lib/output.js
function to_ascii(str) {
return str.replace(/[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f\u007f-\uffff]/g, function (ch) {
var code = get_full_char_code(ch, 0).toString(16);
if (code.length <= 2) {
while (code.length < 2) code = "0" + code;
return "\\x" + code;
} else {
while (code.length < 4) code = "0" + code;
return "\\u" + code;
}
});
};
function get_full_char_code(str, pos) {
// https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates
if (is_surrogate_pair_head(str.charAt(pos))) {
return 0x10000 + (str.charCodeAt(pos) - 0xd800 << 10) + str.charCodeAt(pos + 1) - 0xdc00;
}
return str.charCodeAt(pos);
}
function is_surrogate_pair_head(code) {
if (typeof code === "string")
code = code.charCodeAt(0);
return code >= 0xd800 && code <= 0xdbff;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment