In this article we will learn how to loop through object entries.
It is very common to get first letter of a string in JavaScript.
There is more than one way to solve this problem:
- Using
slice()
method - Using
charAt()
method - Using
at()
method - Using
subString()
method
Problem
Now we have a problem, which is that we want to get the first letter of the string.
Imagine we have a string like this:
"Hello World!"
And we want to get the first letter.
"H"
How to solve this problem?
As we said before, we have more than one solution and in this tutorial we will explain all of them.
Get first letter using slice()
method
We can use slice
method to get the first letter of string in JavaScript.
Example
// String
const myString = "Hello World!";
// Get letters from `0` to `1`
// (first letter)
const firstLetter = myString.slice(0, 1);
// Result:
console.log(firstLetter);
Output
H
The slice()
method returns a shallow copy of a portion of an array into a new array object selected from start to end (Source: MDN)
Get first letter using charAt()
method
We can use charAt()
method to get first letter of string.
Example
// String
const myString = "Hello World!";
// Get first letter
const firstLetter = myString.charAt(0);
// Result:
console.log(firstLetter);
Output
H
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. (Source: MDN)
Get first letter using at()
method
We can use at()
method to get first letter as well.
Example
// String
const myString = "Hello World!";
// Get first letter
const firstLetter = myString.at(0);
// Result:
console.log(firstLetter);
Output
H
Get first letter using subString()
method
We can use subString
method to get first letter as well.
// String
const myString = "Hello World!";
// Get first letter
const firstLetter = myString.substring(0, 1);
// Result:
console.log(firstLetter);
Output
H
The substring() method returns the part of the string from the start index up to and excluding the end index, or to the end of the string if no end index is supplied. (Source: MDN)
Thank you for reading
Thank you for reading my blog. 🚀