Get the Nth Character in a String using JavaScript

avatar

Borislav Hadzhiev

Fri Nov 05 20212 min read

banner

Photo by Ben White

Get the Nth Character in a String using JavaScript #

Use the charAt() method to get the nth character in a string, e.g. str.charAt(1) gets the second character in the string. The only parameter the charAt method takes is the index of the character to be returned. If the index does not exist in the string, an empty string is returned.

index.js
const str = 'one two'; // โœ… Using charAt console.log(str.charAt(1)); // ๐Ÿ‘‰๏ธ "n" console.log(str.charAt(2)); // ๐Ÿ‘‰๏ธ "e" // ๐Ÿ‘‡๏ธ Count backwards console.log(str.charAt(str.length - 1)); // ๐Ÿ‘‰๏ธ "o"

The String.charAt method takes an integer between 0 and string.length - 1 and returns the corresponding character.

Indexes are zero-based in JavaScript, meaning the index of the first character in a string is 0, and the index of the last - string.length - 1.

When passed an index out of bounds, the charAt() method returns an empty string.

index.js
console.log(''.charAt(5)); // ๐Ÿ‘‰๏ธ ""

You can count backwards, by subtracting the number of characters from the string's length. For example, string.length - 2 gives us the second to last character in the string.

index.js
const str = 'one two'; console.log(str.charAt(str.length - 2)); // ๐Ÿ‘‰๏ธ "w"

An alternative approach is to use bracket notation.

Use bracket notation to get the nth character in a string, e.g. str[0] returns the first character in the string. When provided an index that does not exist in the string, you get an undefined value back.

index.js
const str = 'one two'; // โœ… Using bracket notation console.log(str[1]); // ๐Ÿ‘‰๏ธ "n" console.log(str[2]); // ๐Ÿ‘‰๏ธ "e" // ๐Ÿ‘‡๏ธ Count backwards console.log(str[str.length - 1]); // ๐Ÿ‘‰๏ธ "o"
You will most commonly see bracket [] notation being used to access a string at a specific index.

The bracket notation approach differs from the charAt method in that, it returns undefined when provided an index that does not exist in the string.

index.js
console.log(''[5]); // ๐Ÿ‘‰๏ธ undefined

You can also use bracket notation to count backwards, simply subtract the number of characters from the string's length.

index.js
const str = 'one two'; console.log(str[str.length - 2]); // ๐Ÿ‘‰๏ธ "w"

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee