Open In App

How to Iterate Over Characters of a String in JavaScript ?

Last Updated : 06 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Imagine you have a sentence written on a piece of paper. In JavaScript, strings are like those sentences. You can go through each letter one by one, just like you would read the sentence word by word. This process of going through each character is called iteration. There are different ways to iterate over characters in JavaScript and let’s discuss one by one.

iterate-characters-of-string

There are several methods that can be used to Iterate over characters of a string in JavaScript, which are listed below:

1. Using for Loop

In this approach, we are using a for loop to iterate over a string’s characters by indexing each character based on the length of the string and accessing characters at each index.

Syntax:

for (statement 1 ; statement 2 ; statement 3){
code here...
};

Example: In this example, we are using the above-explained method.

Javascript
const str = "GeeksforGeeks";
for (let i = 0; i < str.length; i++) {
    console.log(str[i]);
};

Output
G
e
e
k
s
f
o
r
G
e
e
k
s

2. Using for…of Loop

In this approach, we Iterate over characters of a string using a for…of loop, which directly iterates through each character in the string without the need for indexing.

Syntax:

for ( variable of iterableObjectName) {
...
}

Example: In this example we are using the above-explained approach.

Javascript
const str = "Geeks";
for (const char of str) {
    console.log(char);
};

Output
G
e
e
k
s

3. Using forEach() Method

In this approach, we are using forEach() method on an array created from the string to iterate through characters individually.

Syntax:

array.forEach(callback(element, index, arr), thisValue)

Example: In this example we are using forEach() method to itrate characters of our given string.

Javascript
const str = "Geeks";
Array.from(str).forEach(elem => {
    console.log(elem);
});

Output
G
e
e
k
s

4. Using split() Method

In this approach, we Split the string into an array of characters using split(), then iterate through the array to process each character individually.

Syntax:

str.split('')

Example: In this example we are using above-explained approach.

Javascript
let str = "Geeks";
let result = str.split('');
result.forEach(char => {
    console.log(char);
});

Output
G
e
e
k
s

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads