Converting Characters to ASCII in JavaScript
I first take a string input and change it into a split array, but then I need to change that spl开发者_开发百科it array in ASCII to be evaluated. How do I do that?
A string input is technically already an array of characters.
You can do the following
asciiKeys = [];
for (var i = 0; i < string.length; i ++)
asciiKeys.push(string[i].charCodeAt(0));
like this?
var str= document.URL;
var ascii= str.split('').map(function(itm){
return itm.charCodeAt(0);
});
var str2=ascii.map(function(itm, i){
return '#'+i+'=0x'+itm.toString(16)+' ('+String.fromCharCode(itm)+')';
}).join('\n');
alert('original string='+ str+'\nascii codes:\n'+str2);
/* returned value:
original string=http://localhost/webworks/ghost.html
ascii codes:
#0=0x68 (h)
#1=0x74 (t)
#2=0x74 (t)
#3=0x70 (p)
#4=0x3a (:)
#5=0x2f (/)
#6=0x2f (/)
#7=0x6c (l)
#8=0x6f (o)
#9=0x63 (c)
#10=0x61 (a)
#11=0x6c (l)
#12=0x68 (h)
#13=0x6f (o)
#14=0x73 (s)
#15=0x74 (t)
#16=0x2f (/)
#17=0x77 (w)
#18=0x65 (e)
#19=0x62 (b)
#20=0x77 (w)
#21=0x6f (o)
#22=0x72 (r)
#23=0x6b (k)
#24=0x73 (s)
#25=0x2f (/)
#26=0x67 (g)
#27=0x68 (h)
#28=0x6f (o)
#29=0x73 (s)
#30=0x74 (t)
#31=0x2e (.)
#32=0x68 (h)
#33=0x74 (t)
#34=0x6d (m)
#35=0x6c (l)
*/
let str = 'MyString';
let charCodes = [...str].map(char => char.charCodeAt(0));
console.log(charCodes);
// [77, 121, 83, 116, 114, 105, 110, 103]
精彩评论