Javascript - String Character Methods


Two methods from String class can access specific characters in the string: charAt() and charCodeAt().

These methods each accept a single argument, which is the character's zero-based position.

The charAt() method returns the character in the given position as a single-character string.

var stringValue = "hello world";
console.log(stringValue.charAt(1));   //"e"

The character in position 1 of "hello world" is "e", so calling charAt(1) returns "e".

To get the character's character code instead of the actual character, use charCodeAt().

var stringValue = "hello world";
console.log(stringValue.charCodeAt(1));   //outputs "101"

This example outputs "101", which is the character code for the lowercase "e" character.

You can use bracket notation with a numeric index to access a specific character in the string:

var stringValue = "hello world";
console.log(stringValue[1]);   //"e"

fromCharCode() Method

fromCharCode() takes one or more character codes and convert them into a string.

This is the reverse operation from the charCodeAt() instance method.


console.log(String.fromCharCode(104, 101, 108, 108, 111)); //"hello"


Related Topics