6

I first take a string input and change it into a split array, but then I need to change that split array in ASCII to be evaluated. How do I do that?

4 Answers 4

8

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));
Sign up to request clarification or add additional context in comments.

1 Comment

You could just call string.charCodeAt(i) directly.
2

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)
*/

Comments

1

let str = 'MyString';

let charCodes = [...str].map(char => char.charCodeAt(0));

console.log(charCodes);
// [77, 121, 83, 116, 114, 105, 110, 103]

Comments

0

This will initialise an array of a size matching the length of the string, and map each character to its corresponding code:

let str = 'ABCD1234560';
let arr = Array(str.length).fill().map((_, i) => str.charCodeAt(i));
console.log(arr);

This has the advantage of being able to take a slice of the character string. For example, the first 4 characters only:

let str = 'ABCD1234560';
let arr = Array(4).fill().map((_, i) => str.charCodeAt(i));
console.log(arr);

Or iterate over the string directly:

let str = 'ABCD1234560';
let arr = [];
for (let i = 0; i < str.length; i++)
  arr.push(str.charCodeAt(i));
 
console.log(arr);

1 Comment

Your answer could be improved by adding more information on what the code does and how it helps the OP.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.