How to Loop Through a String in JavaScript?

In JavaScript, a string is a sequence of characters that represent textual data. It can be any combination of letters, numbers, special characters, and whitespace enclosed in quotation marks.

To define a string in JavaScript, you can use single quotes(''), double quotes(""), or backticks(``).

For example:

// Different ways of defining a string in Javascript
const str1 = 'This is a string using single quotes.';
const str2 = "This is a string using double quotes.";
const str3 = `This is a string using backticks.`;

All three ways of defining a string are equivalent in JavaScript, so it’s mostly a matter of personal preference which method you want to use.

Let’s say that you have already created a string and now you want to access its each character, how would you do that?

Well, JavaScript has a bunch of different methods that you can use to loop through a string:


1. Loop Through a String using a Regular For Loop

The most common way to loop through a string in JavaScript is to use a regular for loop.

The for loop will iterate through the string one character at a time, starting from the first character and ending at the last.

In this method, we use a counter variable that starts from 0, and increments by 1 in each iteration.

The loop continues until the counter variable reaches the length of the string. To get the length of the string, we use its length property.

Example:

// Create a string
const str = "Hello";

// Loop through the string with for loop
for(let i = 0; i < str.length; i++){
    // Print character at ith index
    console.log(str[i]);
}

Output:

H
e
l
l
o

2. Loop Through a String using For…of Loop

Another commonly used approach to loop through a string is to use the for...of loop.

This loop is designed specifically for iterating over iterable objects, such as arrays, maps, and strings.

To loop through a string using a for...of loop, you simply declare a variable that represents each character of the string and then use the loop to iterate through the string.

// Create a string
const str = "Hello";

// Loop through the string with for...of loop
for(let char of str){
    // Print current character of the string
    console.log(char);
}

Output:

H
e
l
l
o

In this example, we declare a variable called char inside the for...of loop that represents each character of the string.

One advantage of using a for...of loop is that it can make your code more readable and concise, especially when working with iterable objects.

It also ensures that you don’t accidentally access characters that don’t exist in the string, as the loop automatically stops when it reaches the end of the string.


3. Loop Through a String using For…in Loop

You can also use a for...in loop to loop through a string in JavaScript.

The for...in loop has a similar syntax as the for...of loop. But here the variable gets the index of the current character instead of its value.

// Create a string
const str = "Hello";

// Loop through the string with for...in loop
for(let index in str){
    // Print character at index
    console.log(str[index]);
}

Output:

H
e
l
l
o

While it is possible to use a for...in loop to iterate through a string in JavaScript, still it is not recommended, as for...in loops are designed for iterating over the properties of an object, not the elements of an array or string.


4. Loop Through a String using a While Loop

Another way to loop through a string is to use a while loop.

In this method, we initialize a counter variable to zero before entering the loop and then increment the counter variable by one in each iteration of the loop.

The loop continues until the counter variable is equal to the length of the string.

// Create a string
const str = "Hello";

// Initialize the counter 
let i = 0;

// Run the loop until i reaches length
while (i < str.length) {
    // Print the character at index i
    console.log(str[i]);
    
    // Increment the counter by one
    i++;
}

Output:

H
e
l
l
o

5. Loop Through a String using forEach() Method

The forEach() method is a very well-known method to iterate over the arrays in JavaScript.

But unfortunately, we can not directly use it to loop through strings.

If we want to loop through the strings with the forEach() method, we have to first convert the string into an array and then apply the forEach() method on the resulting array.

To convert the string to an array, you can either use the String.split() method, or the spread syntax [...str].

// Create a string
const str = "Hello";

// Convert string to character array
const charArr = str.split('');

// Call the forEach() method
charArr.forEach(function(char){
    
    // Print each character
    console.log(char);
    
});

Output:

H
e
l
l
o

That’s all for the day. Happy Coding.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.