JavaScript String charAt()

Last Updated On
Saturday 9th Apr 2022

The String charAt() method

The JavaScript String charAt() method returns the character at a specified index (position) in a string

Syntax

	str.charAt(index)
	
  • Here str is a String

Parameters

The charAt() method takes in

  • index – (Required) – A Number – The index (position) of the character.
  • If number is not provided, the default value is used.

Return Value

  • A string – The character at the specified index.

Note: charAt() returns an empty string if index is out of range.

Examples

Get First character in the String

	const text = "Hello World";
const letter = text.charAt(0);
// If Number is not provided , default used
const letter2 = text.charAt();
console.log(letter)
console.log(letter2)
	

Output

	H
H
	

Get Third character in the String

	const text = "Hello World";
const letter = text.charAt(2);
console.log(letter)
	

Output

	l
	

Get Last character in the String

	const text = "Hello World";
const letter = text.charAt(text.length - 1);
console.log(letter)
	

Output

	d