Skip to content

JavaScript charAt() | String method

  • by

Using the charAt() method you can get the character at a specified position in a given string. This method returns a new string consisting of the single UTF-16 code unit located at the specified offset in the string.

  • str: This is the string from which you want to retrieve the character.
  • index: This is the index of the character you want to access within the string.

The charAt() method returns the character at the specified index as a string. If the index is out of range (i.e., less than 0 or greater than or equal to the length of the string), it returns an empty string.

JavaScript charAt()

A simple example code gets the character by index.

<!DOCTYPE html>
    const string = "Hello World!"

    // finding character at index 1
    let index1 = string.charAt(1);

    console.log("Character at index 1 " , index1);


JavaScript charAt String method

Without passing the parameter in charAt() will return character at index 0 which is "H". Because if no index value is passed in the charAt() method. The default index value is 0.

If there is no element in the index value the charAt() method returns an empty string

let sentence = "Happy Birthday to you!";

// finding character at index 100 
let result = sentence.charAt(100);


Output: <empty string>

More Example

Get the last character in a string

let text = "HELLO WORLD";
let letter = text.charAt(text.length-1);

Comment if you have any doubts or suggestions about this JS basic method.

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 *