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
- Loop through string in javascript using for each loop
- Loop through string in javascript using for of loop
- Loop through string in javascript using for in loop
- Iterate through string in javascript using map
Loop through string in javascript using for loop
Example:-
Print each letter of the string “Javascript” followed by ‘ * ‘ after each letter
Function:-
Frequently Asked:
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:
- Javascript: Replace special characters in a string
- Javascript: Replace all occurrences of string (4 ways)
- Javascript: String replace all spaces with underscores (4 ways)
- Javascript: Check if string is url
We hope this article helped you to iterate through a javascript string or process each letter of a javascript string. Good Luck !!!