Sunday, November 14, 2021

JavaScript Character to ASCII Using String.charCodeAt() Function

1. Overview

In this tutorial, we will learn how to use the String object charCodeAt() function in javascript.

String.charCodeAt() function is used to convert the character to ascii code.

This method returns the integer value that is in the range from 0 to 65535 representing the UTF 16 standard code.

2. Syntax of String.charCodeAt()


Below is the syntax
charCodeAt(index)
Unicode points range from 0 to 1114111. The first 128 codes denote the ascii characters.

3. JavaScript Character to ASCII Using String.charCodeAt() Function


charCodeAt() can not take many arguments. It expects to pass only one argument.

String.charCodeAt() Example:
var sentense = 'hello welcome to the blog';

var index = 4;

console.log(sentense.charCodeAt(index));
console.log(sentense.charCodeAt(0));
console.log(sentense.charCodeAt(1));
console.log(sentense.charCodeAt(2));

Output:
111
104
101
108

4. Javascript String.charCodeAt() With Multiple Arguments


As per the syntax, we should not pass many arguments to charCodeAt() function but if the developer passes multiple parameters then what will happen?

Look at the below example and its output.
var sentense = 'hello welcome to the blog';
console.log(sentense.charCodeAt(0, 1, 2, 3));

Output:
104
Based on the output, this method takes into consideration only the first argument value. The remaining arguments are discarded.

So, passing the multiple arguments does not affect the functionality but it is not suggested to use.

5. Conclusion


In this article, we have seen how to use and convert character to ascii using the String.charCodeAt() function in Javascript.



No comments:

Post a Comment