Table of Contents
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.
1 2 3 4 5 6 7 |
var str='Java2blog'; console.log("2nd character in Java2blog: ",str.charAt(1)); // Index out of bound console.log("20th character in Java2blog ",str.charAt(20)); |
Output
1 2 3 4 |
2nd character in Java2blog: a 20th character in Java2blog |
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)
.
1 2 3 4 |
var str='Java2blog'; console.log("2nd last character in Java2blog: ",str.charAt(str.length-2)); |
Output
1 2 3 |
2nd last character in Java2blog: o |
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.
1 2 3 4 5 6 7 |
var str='Java2blog'; console.log("2nd character in Java2blog: ",str[1]); // Index out of bound console.log("20th character in Java2blog ",str[20]); |
Output
1 2 3 4 |
2nd character in Java2blog: a 20th character in Java2blog undefined |
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]
.
1 2 3 4 |
var str='Java2blog'; console.log("2nd last character in Java2blog: ",str[str.length-2]); |
Output
1 2 3 |
2nd last character in Java2blog: o |
Further reading:
That’s all about how to get nth character in String in JavaScript.