`String.prototype.symbolAt()` (improved `String.prototype.charAt()`)

Domenic Denicola domenic at domenicdenicola.com
Sat Oct 19 10:54:28 PDT 2013


From: Mathias Bynens [mailto:mathias at qiwi.be]


> This brings us back to the earlier discussion of whether something like `String.prototype.codePoints` should be added: http://esdiscuss.org/topic/how-to-count-the-number-of-symbols-in-a-string It could be a getter or a generator… Or does `for…of` iteration handle this use case adequately?

It sounds like you are proposing a second name for `String.prototype[Symbol.iterator]`, which does not sound very useful.

A property for the string's "real length" does seem somewhat useful, as does a method that does random-access on "real characters." Certainly more useful than the proposed symbolAt/at. But I suppose we can pave whatever cowpaths arise.

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;
  }
});
```

This would allow you to e.g. find the character in the "real" middle of a string with code like

```js
var middleIndex = Math.floor(theString.realLength / 2);
var middleRealCharacter = theString.realCharacterAt(middleIndex);
```



More information about the es-discuss mailing list