Get Nth Character in String in JavaScript

In this post, we will see how to get Nth Character in String in JavaScript.

Using charAt() method

To get nth character in String, you can use String’s charAt() method.

chatAt() method accepts index as an argument and return the character at the given index. If index is out of bound for string, charAt() method returns empty String.

For example:
str.charAt(1) will return second character in the String.

Let’s see with the help of example.

Output

You can also use str.length to get characters from backwards.

For example:
To get second last character in the string, you can use str.charAt(str.length-2).

Output

Using square brackets

To get nth character in String, you can use square bracket notation.

Bracket notation is way to get character at particular index in String. If index is out of bound for string, charAt() method returns undefined String.

For example:
str[1] will return second character in the String.

Let’s see with the help of example.

Output

You can also use str.length to get characters from backwards.

For example:
To get second last character in the string, you can use str.charAt[str.length-1].

Output

That’s all about how to get nth character in String in JavaScript.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *