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:
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
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; // Result: console.log(letter);
Get a letter from a string using
We can get a letter from a string using
charAt method as well.
// String const string = "Hello World!"; // Get "W" const letter = string.charAt(6); // Result: console.log(letter);
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. 🚀