DEV Community

Nahid Hasan
Nahid Hasan

Posted on

Five Cool Ways to Iterate over JavaScript String

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

Oldest comments (2)

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