String.prototype.charCodeAt
String.fromCharCode()
String.prototype.toUtfArray = function() { return this.split('').reduce(function(a, c) { var code = c.charCodeAt(0); a.push(code >> 8); a.push(code & 0x0ff); return a; }, []); }; String.fromUtfArray = function(a) { // 长度偶数个 否则前面补0 if (a.length % 2 ===1) { a.unshift(0); } var wa = [], code = 0; for (var i = 0; i< a.length; i++) { if (i%2===0) { code = a[i] << 8; } else { code |= a[i]; wa.push(code); } } return wa.map(function(c) { return String.fromCharCode(c); }).join(''); };
test:
var s1 = "你好a"; var a = s1.toUtfArray(); // [79, 96, 89, 125, 0, 97] console.log(a.toString()); var s2 = String.fromUtfArray(a); console.log(s2); // "你好a"