How to use charAt() Method with while Loop In Javascript
In this approach, we use the charAt() method to access each character in the string. We combine it with a while loop that iterates through each index of the string.
Syntax:
let index = 0;
while (index < str.length) {
let char = str.charAt(index);
// code here...
index++;
}
Example: In this example, we use the charAt() method within a while loop to iterate over each character in the given string.
const str = "w3wiki";
let index = 0;
while (index < str.length) {
console.log(str.charAt(index));
index++;
}
Output
G e e k s f o r G e e k s
How to Iterate Over Characters of a String in JavaScript ?
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.
There are several methods that can be used to Iterate over characters of a string in JavaScript, which are listed below:
Table of Content
- Using for Loop
- Using for…of Loop
- Using forEach() Method
- Using split() Method