Skip to content

Convert JavaScript string to ASCII Array | Example code

  • by

Use a for-loop to loop through the given string to get ASCII code, and use charCodeAt() method. A charCodeAt() method retrieves a Unicode value (or ASCII code) for a character at a specific position in a string.

Assign that Unicode value to a variable and add that value into the array.

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

JavaScript string to ASCII Array

HTML example code:-

<!DOCTYPE html>
<html>
<body>
   <script>
     function getCharCodes(s){
       let charCodeArr = [];

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

     return charCodeArr;
  }

  console.log(getCharCodes("Hello world"));
</script>
</body>
</html>

Output:

Convert JavaScript string to ASCII Array

Do comment if you have any doubts and suggestions on this JS String topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *