Photo by Yurii Stupen on Unsplash
Before we start, we need to come back to a much more basic question.
How to Access a Single Character of a String
Nowadays with ECMAScript 2015 (ES6), there are two ways of accessing a single character:
This method of the string object has been around for some time now and can be seen as the classic approach. It?s supported even in oldest browsers.
The second method is accessing a character via bracket notation:
This approach has been introduced with ECMAScript 2015 and seems to be more convenient. Furthermore, it allows you to treat a string like an array-like structure. This enables a couple of iteration methods, as we?ll see soon.
Which method is preferable?
A downside of charAt() might be readability. However, it?s compatible with old browsers like IE7. Another argument against bracket notation is it can?t be used for assigning a character:
This can be confusing, especially because there won?t be a warning.
In my personal opinion, bracket notation is more convenient to write and read. Compatibility issues should be solved by transpiling instead of not using the desired feature.
Popular Ways to Iterate Strings
The following list of techniques doesn?t claim to be complete. It?ll show some of the most frequently used approaches.
In order to demonstrate the processing of the single characters of our string, we?ll use the following function:
The classic approach ? a simple for loop:
While a bit cumbersome to write and read, this is the fastest known method.
This statement was introduced with ECMAScript 2015 and can be used with iterable objects. It?s more convenient to write than a classic for loop if you don?t care about the current index in the loop body.
This is the functional version of a for loop. Many people prefer it over for?of and for loops because it?s a higher-order function, and it helps to stick to a programming style that leverages immutability (see the Airbnb style guide in the references).
One downside is you need to convert the string into an array before iterating. If performance really matters in your use case (and it usually doesn?t), it might not be your first choice.
I advise you to pick the most readable technique and only care for speed optimization if you have a performance problem and to solve compatibility issues through transpiling.
- MDN Web Docs: Character access