DEV Community

Charles Amakoye
Charles Amakoye

Posted on

Three ways of accessing string characters in JavaScript

How do we access characters in a string? Well, in this post we look at three ways that we can use to access a character at a particular index, i, in a string. In a string characters are indexed from left to right. For instance, in a string named str the first character is at index 0, while the last is at index str.length-1

1. using charAt() method

This method will return the character at a specified index in a string. The method takes in a parameter, an integer that represents the index of the character to be returned. The syntax for usage is string.charAt(index).

let str = 'string';
console.log(str.charAt(0)); // s
Enter fullscreen mode Exit fullscreen mode

If no character is found, the method returns an empty string.

let str = 'string';
console.log(str.charAt(999)); // ''
Enter fullscreen mode Exit fullscreen mode

2. using square brackets notation []

Another way of accessing a character in a string is to using the square bracket. for example;

let str = 'string';
console.log(str[1]); // t
Enter fullscreen mode Exit fullscreen mode

When we try to access a character whose index is larger than the string length, the Square brackets [] returns undefined.

let str = 'string';
console.log(str[999]); // undefined
Enter fullscreen mode Exit fullscreen mode

3. using for...of loop

We can also access string characters by simply iterating over its characters using the for...of loop

let str = 'string';
for(let char of str){
console.log(char); //s,t,r,i,n,g
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)