➤ How to Code a Game
➤ Array Programs in Java
➤ Java Inline Thread Creation
➤ Java Custom Exception
➤ Hibernate vs JDBC
➤ Object Relational Mapping
➤ Check Oracle DB Size
➤ Check Oracle DB Version
➤ Generation of Computers
➤ XML Pros & Cons
➤ Git Analytics & Its Uses
➤ Top Skills for Cloud Professional
➤ How to Hire Best Candidates
➤ Scrum Master Roles & Work
➤ CyberSecurity in Python
➤ Protect from Cyber-Attack
➤ Solve App Development Challenges
➤ Top Chrome Extensions for Twitch Users
➤ Mistakes That Can Ruin Your Test Metric Program
Iterate Through String in JavaScript | Strings in JavaScript or any other programming language are handy for holding data in text format. The String is an Object in JavaScript which has many pre-built methods. In this article, we will discuss how to iterate through a string in JavaScript using those built-in methods.
Iterate Through String in JavaScript Using the index number
This method uses the str.length method along with a for loop.
const str = "Hello";
for (let i = 0; i < str.length; i++) {
console.log(str[i]);
}
Output:-
H
e
l
l
o
In the above example, the condition of the for loop is set in such a way that the variable “i” takes value in increasing order starting from 0 till it reaches the length of the String.
The value of “i” is then used to slice the String at the said index using the [ ] operator.
Iterate Through Characters In A String Javascript Using the for… in loop
A special keyword “in” is used in this method to iterate through a string.
str = "Hello";
for (i in str) {
console.log(str[i]);
}
Output:-
H
e
l
l
o
In the above example, the special keyword in is used in the for loop condition. The in keyword is used to iterate through the index of its operand which in our case is the variable str.
The string is then sliced at the index using the [ ] operator, just like we did in the previous example.
Javascript Iterate Over String Using the for… of loop
In this method, a special keyword “of” is used to iterate through the characters of a string.
str = "Hello";
for (char of str) {
console.log(char);
}
Output:-
H
e
l
l
o
In the above example, the condition of for loop uses a keyword called “of”. It directly assigns the value of each character in any iterative object, which is a String in our case. We can thus use the iterating variable directly to print out the results.
Thus we studied how we can iterate through a string in JavaScript using three different methods. Any of the methods can be used depending on the use case and the comfort of the programmer.
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!