To get a character from a string in JavaScript, use the charAt() method. The String charAt() is a built-in JavaScript function that returns a character from a string at the specified index.
Syntax
charAt(index)
Arguments
The charAt() function takes am index. The index is what we need to pass, which is between 0 and string.length-1. If we pass an index that is not valid, then it will return the first character from the string. The default value of this method is 0.
Return value
The charAt() function returns a string which is from UTF-16 code unit.if passed index is greater than string.length-1, it will return empty string.
Example
const string = "Tony stark is greatest avenger ever";
console.log("showing index wise character");
// default index 0
console.log("index 0 : ", string.charAt());
console.log("index 0 : ", string.charAt(0));
console.log("index 1 : ", string.charAt(1));
console.log("index 2 : ", string.charAt(2));
console.log("index 3 : ", string.charAt(3));
// Not valid index number
console.log("index 23223 : ", string.charAt(23223));
Output
showing index wise character
index 0 : T
index 0 : T
index 1 : o
index 2 : n
index 3 : y
index 23223 :
In the first example, we pass nothing in the charAt() method, so by default, it will take an index 0,
In the second example, it will return the first character from the string, which is “T“.
In another example, we pass a valid index number so that it will return a character based on that index. Finally, in the last example, we give an index that is not valid so that it will return an empty string.
Get character from string using for loop
We can also get a character from a string by iterating that string precisely like an array using for loop.
const string = "Tony stark";
for (let i = 0; i < string.length; i++) {
console.log(`index ${i} : `, string[i])
}
Output
index 0 : T
index 1 : o
index 2 : n
index 3 : y
index 4 :
index 5 : s
index 6 : t
index 7 : a
index 8 : r
index 9 : k
In the above example, first, we iterate the whole string using for loops. In the for loop, an “i” represents the string’s index. So we can get characters from string by using the “string[i]”. It looks similar to accessing an array.
Which method you should choose to get a character from a string
The best way to get a character from a string is to use JavaScript’s String.charAt() function. The for loop or any loop will take time to iterate every character of the array, which is not the optimal solution, in my opinion.
That’s it for this tutorial.
Related posts
How to Convert String to Char Code in Javascript
How to Convert URL to String in JavaScript

Rushabh Rupani is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. Rushabh has experience with various programming languages and technologies, including PHP, Python, and expert in JavaScript. He is comfortable working in front-end and back-end development.