Loop through string in javascript

There is a general requirement while developing with javascript to loop through a string or process each letter of the text. This article will discuss how to iterate through a string in javascript using different methods and example illustrations.

Table of Contents:-

Loop through string in javascript using for loop

Example:-

Print each letter of the string “Javascript” followed by ‘ * ‘ after each letter

Function:-

function processEachChar(_string)
{
let finalString = '';
for (let i = 0; i < _string.length; i++) {
    finalString = finalString + _string[i] + " * ";
  }
      console.log(finalString);
}

Usage:-

processEachChar("Javascript")

Output:-

J * a * v * a * s * c * r * i * p * t * 

Loop through string in javascript using for each loop

Example:-

Print each letter of the string “Javascript” followed by ‘ * ‘ after each letter

Function:-

function processEachChar(_string)
{
let finalString = '';
_string.split('').forEach(charAtIndex => 
    {
    finalString = finalString + charAtIndex + " * ";
     });
 console.log(finalString)
}

Usage:-

processEachChar("Javascript")

Output:-

J * a * v * a * s * c * r * i * p * t * 

Loop through string in javascript using for of loop

Example:-

Print each letter of the string “Javascript” followed by ‘ * ‘ after each letter

Function:-

function processEachChar(_string)
{
let finalString = '';
for (let charAtIndex of _string) {
    finalString = finalString + charAtIndex + " * ";
}
console.log(finalString)
}

Usage:-

processEachChar("Javascript")

Output:-

J * a * v * a * s * c * r * i * p * t * 

Loop through string in javascript using for in loop

Example:-

Print each letter of the string “Javascript” followed by ‘ * ‘ after each letter

Function:-

function processEachChar(_string)
{
let finalString = '';
for (let i in _string) {
    finalString = finalString + _string[i] +" * ";
}
console.log(finalString)
}

Usage:-

processEachChar("Javascript")

Output:-

J * a * v * a * s * c * r * i * p * t * 

Iterate through string in javascript using map

Example:-

Print each letter of the string “Javascript” followed by ‘ * ‘ after each letter

Function:-

function processEachChar(_string)
{
    let finalString = '';
    _string.split('').map(function(charAtIndex) {
        finalString = finalString +  charAtIndex + " * ";
    });
console.log(finalString)
}

Usage:-

processEachChar("Javascript")

Output:-

J * a * v * a * s * c * r * i * p * t * 

Read More:

We hope this article helped you to iterate through a javascript string or process each letter of a javascript string. Good Luck !!!

Advertisements

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top