DEV Community

loading...

Five Cool Ways to Iterate over JavaScript String

nahidmbstu profile image Nahid Hasan ・1 min read

First

Using Array.from() method

let hello =  "World"

// first

Array.from(hello).map(i => console.log(i))

second

using for ...of loop

// second

for (let char of hello){
  console.log(char)
} 

third

using built in split() method in String()

// third

hello.split("").forEach(i => console.log(i))

fourth

ancient for loop

// fourth

for (let i = 0; i < hello.length ; i++) {
  console.log(hello[i])
}

// five

using fancy generator function and for ... loop

//  five advance 

function* iter(str) {
    let i = 0
    while(i < str.length) {
       yield str[i];
       i++
    }
}

for (let char of iter(hello)){
  console.log(char)
} 

Let Me Know Others . Thanks

Discussion

pic
Editor guide
Collapse
marcellothearcane profile image
marcellothearcane
Object.values('hello')
Collapse
mellen profile image
Matt Ellen
[...'World'].forEach(l => console.log(l));