Skip to content

Instantly share code, notes, and snippets.

@wcccode
Created March 4, 2015 07:55
Show Gist options
  • Save wcccode/60e4aa3df2bb12ee7c71 to your computer and use it in GitHub Desktop.
Save wcccode/60e4aa3df2bb12ee7c71 to your computer and use it in GitHub Desktop.
javascript unicode转义字符相互转化
function fromUnicode (str) {
var runicode = /\\u([a-f0-9]{4})/gi;
str += '';
return str.replace(runicode, function (m, hex) {
return String.fromCharCode(parseInt(hex, 16));
});
}
function toUnicode (str) {
str += '';
var result = [],
unicode;
for (var i = 0, len = str.length; i < len; i = i + 1) {
// The unicode format is `\u{hexCharCode}`
// If the `String(hexCharCode).length < 4`, left pad with '0'.
unicode = str.charCodeAt(i).toString(16);
unicode = '\\u0000'.slice(0, -unicode.length) + unicode;
result.push(unicode);
}
return result.join('');
}
console.log(fromUnicode("\\u8F7F\\u8F66"));//轿车
console.log(String.fromCharCode(23458));//客
console.log("客".charCodeAt(0).toString(16));//5ba2
console.log(toUnicode("客"));//\u5ba2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment