The String object's charAt() method

The String object's charAt() method returns the character at a specific position in a string.

Syntax

string.charAt(offset)

Parameters

offset:

  • The offset specifies the position of the character in the string that the charAt() method will return. The first character in the string has an offset of 0 and the last one has an offset that is length - 1, where length is the number of characters in the string. If you do not specify an offset or if it cannot be converted to an integer, the first character in the input string will be returned by default. If the offset is out of range, which means it is greater than the length of the string, an empty string will be returned.

Return value

The charAt() method returns a string containing the character in an input string that is at the position specified by the offset.

Examples

Example 1: The charAt() method returns the character at a specific position in a string

In the code below, the function charAtEx1() logs the characters in the first, second and last position in the string str.

function charAtEx1() {
  let str = "Hello world!";

  // Returns the first character ("H")
  Logger.log(str.charAt(0));

  // Returns the second character ("e")
  Logger.log(str.charAt(1));

  // Returns the last character ("!")
  let length = str.length;
  Logger.log(str.charAt(length - 1));
}

Output

H

e

!

Example 2: The charAt() method returns the first character by default if you do not specify an offset, or if the offset cannot be converted to an integer

In the code below, the function charAtEx2() demonstrates situations where the offset is either not specified or cannot be converted to an integer. In these situations, the charAt() method returns the first character in the string by default.

function charAtEx2() {
  let str = "Hello world!";

  // Returns the first character by default since
  // the offset is not specified
  Logger.log(str.charAt());

  // Returns the first character by default since
  // the offset cannot be converted to an integer
  Logger.log(str.charAt("&&&**"));
}

Output

H

H

Example 3: The charAt() method returns an empty string if the offset is out of range

In the code below, the function charAtEx3() logs the character at an offset of 12 in the string str. However, since the length of str is 12, its first character has an offset of 0 and its last one has an offset of 11 (12 - 1). Therefore, the offset 12 is out of range and the charAt() method returns an empty string.

function charAtEx3() {
  let str = "Hello world!";

  // Returns an empty string since the offset is
  // out of range.
  Logger.log(str.charAt(13));
}

Output (note: An empty string is logged)

Conclusion

In this tutorial, you learned how to use the charAt() method of the String object to return the character at a specific position in an input string.

Sign up to be notified when I publish new content

By signing up you agree to the Privacy Policy & Terms.