Convert integer array to string in javascript

Here is the 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; 

Conclusion: 中文chinese

Here is the 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); 

conclusion: 䏿chinese

So how do I handle an array in javascript?

+8
javascript utf-8
source share
6 answers

JavaScript strings consist of UTF-16 units of code, but the numbers in your array are UTF-8 bytes. Here is one way to convert a string that 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); 

Converting UTF-8 to UTF-16 in the usual way is likely to be more efficient, but it will require more code.

+18
source share
 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]

+5
source share

Another solution without decodeURIComponent for characters up to 3 bytes (U + FFFF). The function assumes the string is valid UTF-8, not many validation errors ...

 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 } 
+3
source share

The Chinese encoding has another encoding in which one char has a length of more than one byte. When you do it

 for (i in arr){ str+=String.fromCharCode(arr[i]); } 

You convert each byte to char (actually a string) and add it to the str string. What you need to do is connect the bytes together.

I changed my array to this and it worked for me:

 var arr=[20013,25991,99,104,105,110,101,115,101]; 

I got these codes from here .

you can also take a look at this for packing bytes into a string.

+1
source share

It seems the best way these days is:

 function bufferToString(arr){ arr.map(function(i){return String.fromCharCode(i)}).join("") } 
-one
source share

Basically, Javascript treats everything as a string . We can change the string to an integer using parseInt .

We do not need to change the integer per line. Try entering the following code in Javascript:

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

All Articles