In this article we will learn how to get letter from a string in JavaScript.
It is very common to get letter from a string in JavaScript in JavaScript.
Problem
Now we have a simple problem, which is that we want to get a character from the string.
Imagine we have a string like this:
const string = "Hello World!";
And we want to get specific letter from it, for instance W
, so the output will be like this:
W
How to solve this problem?
Fortunately, there is more than one solution to solve this problem, and there is more than one built-in function that will simply do that.
We can solve this problem using:
- Using square brackets
[]
- Using
charAt()
method
Get a letter from a string using square brackets
As we said before, we can use square brackets to get a letter from a string
Let's see an example
// String
const string = "Hello World!";
// Get "W"
const letter = string[6];
// Result:
console.log(letter);
Output
W
Get a letter from a string using charAt
We can get a letter from a string using charAt
method as well.
Example
// String
const string = "Hello World!";
// Get "W"
const letter = string.charAt(6);
// Result:
console.log(letter);
Output
W
The String object's charAt() method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string. (MDN)
Thank you for reading
Thank you for reading my blog. 🚀