DEV Community

Nahid Hasan
Nahid Hasan

Posted on

1 2

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

Top comments (2)

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay