archives

« Bugzilla Issues Index

#2073 — `String.prototype.at` (improved `String.prototype.charAt`)


Proposal from https://mail.mozilla.org/pipermail/es-discuss/2013-October/034240.html:

## String.prototype.at(pos)

NOTE: Returns a single-element String containing the code point at element position `pos` in the String `value` resulting from converting the `this` object to a String. If there is no element at that position, the result is the empty String. The result is a String value, not a String object.

When the `at` method is called with one argument `pos`, the following steps are taken:

01. Let `O` be `CheckObjectCoercible(this value)`.
02. Let `S` be `ToString(O)`.
03. `ReturnIfAbrupt(S)`.
04. Let `position` be `ToInteger(pos)`.
05. `ReturnIfAbrupt(position)`.
06. Let `size` be the number of elements in `S`.
07. If `position < 0` or `position ≥ size`, return the empty String.
08. Let `first` be the code unit at index `position` in the String `S`.
09. Let `cuFirst` be the code unit value of the element at index `0` in the String `first`.
10. If `cuFirst < 0xD800` or `cuFirst > 0xDBFF` or `position + 1 = size`, then return `first`.
11. Let `cuSecond` be the code unit value of the element at index `position + 1` in the String `S`.
12. If `cuSecond < 0xDC00` or `cuSecond > 0xDFFF`, then return `first`.
13. Let `second` be the code unit at index `position + 1` in the string `S`.
14. Let `cp` be `(first – 0xD800) × 0x400 + (second – 0xDC00) + 0x10000`.
15. Return the elements of the UTF-16 Encoding (clause 6) of `cp`.

The `length` of the `at` function is `1`.

NOTE: The `at` function is intentionally generic; it does not require that its `this` value be a String object. Therefore it can be transferred to other kinds of objects for use as a method.

Here’s a polyfill based on this algorithm: http://mths.be/at

Tests: https://github.com/mathiasbynens/String.prototype.at/blob/master/tests/tests.js


This is already being tracked as part of the standard proposal process so a bug is not necessary.