How to iterate through a string in JavaScript

Last updated on Sep 5, 2022 by Suraj Sharma



In this tutorial, you will learn two ways to iterate through a string in JavaScript


Using for loop statement


String.CharAt() function is use to get the string's character at index i


Example


const str = 'hello world'

for(let i=0;i<str.length;i++){
    console.log(str.charAt(i));
}


Using for..of statement


We can also use for..of statement to iterate through a string in JavaScript


Example


for(let c of "hello") {
  console.log(c)
}


Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.