Skip to content

Convert integer array to string at javascript

Here is php code:

foreach ($arr as $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){

the output is: 中æchinese

So how should I process the array at javascript?



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.

User contributions licensed under: CC BY-SA
8 People found this is helpful