How to Convert Ascii Codes to Characters in JavaScript
Table of Contents
ASCII is the abbreviation for American Standard Code for Information Interchange.
This is an information standard, similar to unicode, that defines a standard for the representation of text and other information in computers.
In more simpler terms, it basically assigns a unique code for each character in a text.
For example, the letter a
has the code 97
in ASCII.
In this post, we'll learn how to convert from ASCII codes to characters in JavaScript.
How to Convert ASCII Codes to Characters
To learn how to convert an ASCII code to a character, let's start with the code we want to convert.
JAVASCRIPTconst code = 97;
Now we can use this along with the String.fromCharCode()
method to convert the code to a character.
JAVASCRIPTconst code = 97;
const character = String.fromCharCode(code);
console.log(character);
BASHa
This method is simple, it takes a single parameter, which is a number representing the ASCII code of the character we want to convert.
It will return back a string, which is the character we want.
The cool thing about this method is that it can convert multiple ASCII codes at once and return it in a single string.
JAVASCRIPTconst codes = [97, 98, 99];
const characters = String.fromCharCode(...codes);
console.log(characters);
BASHabc
Alternatively, you can just pass them one by one, like this:
JAVASCRIPTconst string = String.fromCharCode(97, 98, 99);
console.log(string);
BASHabc
If you want, you can instead get back an array of the converted strings by using the map
function.
JAVASCRIPTconst codes = [97, 98, 99];
const characters = codes.map(code => String.fromCharCode(code));
console.log(characters);
BASH(3) ["a", "b", "c"]
Conclusion
In this post, we learned how to convert an ASCII code to a character, and how to convert multiple ASCII codes at once.
Simply use the String.fromCharCode()
method which takes the number you want to convert and returns the character.
Thanks for reading!
- Getting Started with Express
- Create an RSS Reader in Node
- Getting Started with Electron
- How to deploy a .NET app using Docker
- How to deploy a Deno app using Docker
- Getting Started with Deno
- Getting Started with Sass
- Using Puppeteer and Jest for End-to-End Testing
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications