Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
699 views
in Technique[技术] by (71.8m points)

utf 8 - Convert integer array to string at javascript

Here is php code:

$arr=array(228,184,173,230,150,135,99,104,105,110,101,115,101);
$str='';
foreach ($arr as $i){
    $str.=chr($i);
}
print $str;

the output is: 中文chinese

Here is javascript code:

var arr=[228,184,173,230,150,135,99,104,105,110,101,115,101];
var str='';
for (i in arr){
    str+=String.fromCharCode(arr[i]);
}
console.log(str);

the output is: ??-?chinese

So how should I process the array at javascript?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

JavaScript strings consist of UTF-16 code units, yet the numbers in your array are the bytes of a UTF-8 string. Here is one way to convert the string, which uses the decodeURIComponent() function:

var i, str = '';

for (i = 0; i < arr.length; i++) {
    str += '%' + ('0' + arr[i].toString(16)).slice(-2);
}
str = decodeURIComponent(str);

Performing the UTF-8 to UTF-16 conversion in the conventional way is likely to be more efficient but would require more code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...