Thought leadership from the most innovative tech companies, all in one place.

JavaScript Algorithm: Convert String Characters into ASCII

Create a function that will return an array containing the ASCII codes of each character from a string.

Photo by Alexander Sinn on Unsplash

Photo by Alexander Sinn on Unsplash

We are going to write a function called getCharCodes that will accept a string s as an argument.

The goal of the function is to return an array containing the ASCII codes of each character from our string input.

Example:

getCharCodes("I like JavaScript")

//output: [73,32,108,105,107,101,32,74,97,118,97,83,99,114,105,112,116]

ASCII-Table.svg: ZZT32derivative work: LanoxxthShaddow, Public domain, via Wikimedia Commons

ASCII-Table.svg: ZZT32derivative work: LanoxxthShaddow, Public domain, via Wikimedia Commons

The image shows an ASCII table. If you look at each character in the string from our example, you'll see its decimal equivalent under the Decimal column.

We begin our function by creating an empty array and assigning it to a variable called charCodeArr. This is the array that will contain our ASCII code for each character in s.

let charCodeArr = [];

Next, we will use a for-loop to loop through our string. To obtain our ASCII code, we will use a JavaScript string method called charCodeAt(). What that method does is retrieves a Unicode value (or ASCII code) for a character at a specific position in a string.

We assign that Unicode value to a variable called code then we add that value into the charCodeArr array.

for(let i = 0; i < s.length; i++){
    let code = s.charCodeAt(i);
    charCodeArr.push(code);
}

After we loop through the string, we return the array.

return charCodeArr;

Here is the full function:

That's it for this topic. Thank you for reading.




Continue Learning