JavaScript – Iterate over Characters of a String
To iterate over characters of a given string in JavaScript, use For loop to iterate the index from zero to length of the string, and during each iteration access the respective character using index.
The sample code to iterate over the characters of a given string str
using For loop is
</>
Copy
for (let index=0; index < str.length; index++) {
let char = str[index];
}
Example
In the following example, we take a string str
, iterate over the characters of the string, and display each of the character in pre#output.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var str = 'apple';
for (let index=0; index < str.length; index++) {
let char = str[index];
document.getElementById('output').innerHTML += index + " - " + char + '\n';
}
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned how to iterate over the characters of a given string in JavaScript, with example program.