Last active
April 26, 2024 03:29
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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