Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 926
solomon_wzs Avatar asked Dec 25 '12 06:12

solomon_wzs


3 Answers

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.

like image 163
PleaseStand Avatar answered Oct 01 '22 14:10

PleaseStand


var arry = [3,5,7,9];
console.log(arry.map(String))

the result will be ['3','5','7','9']

var arry = ['3','5','7','9']
console.log(arry.map(Number))

the result will be [3,5,7,9]

like image 45
ingrid Avatar answered Oct 01 '22 15:10

ingrid


Another solution without decodeURIComponent for characters up to 3 bytes (U+FFFF). The function presumes the string is valid UTF-8, not much error checking...

function atos(arr) {
    for (var i=0, l=arr.length, s='', c; c = arr[i++];)
        s += String.fromCharCode(
            c > 0xdf && c < 0xf0 && i < l-1
                ? (c & 0xf) << 12 | (arr[i++] & 0x3f) << 6 | arr[i++] & 0x3f
            : c > 0x7f && i < l
                ? (c & 0x1f) << 6 | arr[i++] & 0x3f
            : c
        );

    return s
}
like image 32
smrtl Avatar answered Oct 01 '22 16:10

smrtl