Simple for loop can use for in iterate through words in a string JavaScript. And for iterate words in string use split, map, and join methods (functions).
Loop through words in a string JavaScript Example
<!DOCTYPE HTML>
<html>
<body>
<script>
var str = "Hello world"
for (var i = 0; i < str.length; i++) {
console.log(str.charAt(i));
}
</script>
</body>
</html>
Output:
Iterate words in string in JS Example code
<html>
<body>
<script>
var str = "Hello world"
function getStr(str) {
return str.split('')
.map(item => item)
.join('')
}
console.log(getStr(str));
</script>
</body>
</html>
Output:
Do comment if you have any doubts and suggestions on this JS strings topic
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version
Stringloop
var str=”abcdefgh”
for(var i=0; i< str.length; i++){
console.log(str.charAt(i));
}
why i can’t see output when i run the code
Your code is working fine i am getting output.