Looping Through a String

The length Property

The length property has the string length, it simply returns the number of characters in the string:

let str = "hello123";
alert(str.length);            // 8

// the last character
alert(str[str.length - 1]);   // 3

Please note that str.length is a numeric property, not a function. There is no need to add brackets after it.

Use the string index number to loop through a string

for loop

To walk over all the characters of a string, we can use an ordinary for loop, with a loop counter (i) to go through string index from 0 to str.length:

// ordinary for loop
let str = "Buzz";
for (let i = 0; i < str.length; i++) {
  console.log(str[i]);
}
for ... in ...

There exists a special form of the loop: for...in.... This is different from the ordinary for loop that we studied before.

In this loop, the variable i automatically receives the index so that each character can be accessed using str[i].

Example:

// for... in
for (let i in str) {
  console.log(str[i]);
}

The above two kinds of for loop will loop through string str just the same, they all give the same result in the console:

B
u
z
z
for ... of ...

Another way to iterate over a string is to use for item of str. The variable item receives the character directly so you do not have to use the index. If your code does not need the index value of each character, this loop format is even simpler.

Example:

// for ... of ...
for (let char of "Hello") {
  console.log(char);
}

// console result:
H
e
l
l
o

results matching ""

    No results matching ""