To loop over the characters of a string in JavaScript, we can use a for loop, the JavaScript charAt() method, and the length property to loop over each character in the following way.
var example_string = "example";
for( var i=0; i<example_string.length; i++ ){
console.log(example_string.charAt(i));
}
#Output:
e
x
a
m
p
l
e
When working with strings, the ability to work with the characters individually is valuable.
You can loop over the characters of a string variable in JavaScript easily.
String objects are iterable in JavaScript and therefore you can loop over a string.
To loop over the characters of a string in JavaScript, you can use a for loop and loop over each character in the following way.
var example_string = "example";
for( var i=0; i<example_string.length; i++ ){
console.log(example_string.charAt(i));
}
#Output:
e
x
a
m
p
l
e
Examples of Loop Over String in JavaScript
Depending on the situation, you might find it useful to want to loop over the characters of a string.
In JavaScript, we can easily find if a string contains certain characters by looping over each character of the string and seeing if it is one of the given characters or not.
Below is a function that will check if a string has certain characters or not for you in a string using JavaScript. The function will take two strings. We will use nested for loops to check if any character in the second string is contained in the first. If one is found, we will return true. Otherwise, false.
function containsCertainChars(theString, chars){
for( var i=0; i<theString.length; i++ ){
for( var k=0; k<chars.length; k++ ){
if(theString.charAt(i) === chars.charAt(k)){
return true;
}
}
}
return false;
};
console.log(containsCertainChars("Hello World!", "H"));
console.log(containsCertainChars("Hello World!", "olz"));
console.log(containsCertainChars("Hello World!", "z"));
#Output:
true
true
false
Another example of using a for loop to check each char in a string is if we want to check if a string contains uppercase letters in JavaScript.
We can check if a string contains uppercase characters in JavaScript by checking each letter to see if that letter is uppercase in a loop. We will make use of the toUpperCase() and charAt() methods.
Here is our function that will check if there are any uppercase letters in a string.
function checkUppercase(str){
for (var i=0; i<str.length; i++){
if (str.charAt(i) == str.charAt(i).toUpperCase() && str.charAt(i).match(/[a-z]/i)){
return true;
}
}
return false;
};
console.log(checkUppercase("all letters here are lowercase"));
console.log(checkUppercase("We Have some uppercase Letters in this One."));
#Output:
false
true
Hopefully this article has been useful for you to learn how to use a JavaScript for loop to loop over each char in a string.