JavaScript charCodeAt method, to be used on strings, takes an index as an optional parameter. This method returns the Unicode character of the corresponding character specified by the index.

So the syntax is as follows: string.charCodeAt(index).

If the index is not specified, it will have a default value of 0.

JavaScript base

Da zero ad eroe

Entra nel mondo della programmazione web: variabili, funzioni, array, DOM, eventi. Con esercizi pratici e progetti coinvolgenti.

  • 8 ore di corso registrato
  • Più di 50 algoritmi risolti passo passo
  • Livello base — da zero ad eroe
  • 100% online, fruibile quando vuoi

Recall that Unicode is an encoding that assigns a unique number to each alphanumeric character. This encoding is independent of the language used.

For more information, see the following link: unicode encoding.

JavaScript charCodeAt

In this first example we will get the Unicode of the first character of a string.

So here's a possible implementation of the JavaScript charCodeAt method:



var sentence = 'do coding creativo';
var character = sentence.charCodeAt(0);
console.log(character);

So, in the browser console, we get the value 102, which is the corresponding Unicode character of the letter f.

Using the JavaScript charCodeAt method in the last character of a string

In this example we get the Unicode encoding of the last character of a string taken as input.

To do this, it is necessary to use the length property on the string which, remember, returns the number of characters of a given string.

Here is the complete example:



var sentence = 'do coding creativo';
var character = sentence.charCodeAt(sentence.length-1);
console.log(character);

In this case, the value 101 is obtained, which corresponds to the Unicode encoding of the letter o.

Copertina: 50 Algoritmi per imparare JavaScript
📚 Consigliato per te

50 Algoritmi per imparare JavaScript

Una guida step by step per imparare JavaScript con esercizi svolti.

Vedi su Amazon

If we try to obtain the Unicode encoding of an index that does not exist then we will have the value NaN (Not a Number).

Conclusion

In this lesson we have seen some practical examples on using the JavaScript charCodeAt method, in the next lessons we will see many other examples with other methods on strings and arrays.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

JavaScript variables and costants

🐍

Vuoi imparare Python da zero?

Scarica la guida gratuita Python in 10 giorni: 10 lezioni pratiche con esempi ed esercizi, direttamente nella tua email.

📥 Scarica gratis il PDF →