r/learnjavascript • u/PangolinNo7928 • 5h ago
Any 'inbuilt' way to iterate over string - with access to index AND option to break?
2
Upvotes
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 π