r/learnjavascript • u/PangolinNo7928 • Oct 04 '26
Any 'inbuilt' way to iterate over string - with access to index AND option to break?
I've been trying to learn more about iterators - but it doesn't seem like there is a string equivalent of .entries()? myStr[Symbol.iterator].forEach() gives the index and value - but no option to break 😞
For veryyyyyy long strings is my best option for loops? Splitting to create an array? Writing a separate generator function? (assume I only need a single char/index per loop)
Thanks!
Edit - thanks to u/Psionatix for guiding me to Object.entries(myStr), which led me to Array.prototype.entries.call(myStr) - which has the benefit of returning the indexes as integers (vs strings in Object.entries()) Performance is also close enough to for loop for my purposes 🎉
View all comments
Show parent comment
1
u/chikamakaleyley helpful Oct 04 '26
any thoughts on using .charAt(i) vs [i] here?
personally here i lean towards .charAt() just cuz i think the optics makes it obvious at a glance that we're working w a string. Even though str[i] is valid, my brain says to me "we're given these convenient methods for strings, lets use them'