`String.prototype.symbolAt()` (improved `String.prototype.charAt()`)
Mathias Bynens
mathias at qiwi.be
Sun Oct 20 05:02:45 PDT 2013
On 19 Oct 2013, at 12:54, Domenic Denicola <domenic at domenicdenicola.com> wrote:
> My proposed cowpaths:
>
> ```js
> Object.mixin(String.prototype, {
> realCharacterAt(i) {
> let index = 0;
> for (var c of this) {
> if (index++ === i) {
> return c;
> }
> }
> }
> get realLength() {
> let counter = 0;
> for (var c of this) {
> ++counter;
> }
> return counter;
> }
> });
> ```
Good stuff!
To account for [lookalike symbols due to combining marks] [1], just add a call to `String.prototype.normalize`:
Object.mixin(String.prototype, {
get realLength() {
let counter = 0;
for (var c of this.normalize('NFC')) {
++counter;
}
return counter;
}
});
assert('ma\xF1ana'.realLength == 'man\u0303ana'.realLength);
[1]: http://mathiasbynens.be/notes/javascript-unicode#accounting-for-lookalikes
More information about the es-discuss
mailing list