A robust & optimized ES3-compatible polyfill for the String.prototype.at
proposal for ECMAScript 6/7.
Spec bug ticket: https://bugs.ecmascript.org/show_bug.cgi?id=2073
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:
- Let
O
beRequireObjectCoercible(this value)
. - Let
S
beToString(O)
. ReturnIfAbrupt(S)
.- Let
position
beToInteger(pos)
. ReturnIfAbrupt(position)
.- Let
size
be the number of elements inS
. - If
position < 0
orposition ≥ size
, return the empty String. - Let
first
be the code unit at indexposition
in the StringS
. - Let
cuFirst
be the code unit value of the element at index0
in the Stringfirst
. - If
cuFirst < 0xD800
orcuFirst > 0xDBFF
orposition + 1 = size
, then returnfirst
. - Let
cuSecond
be the code unit value of the element at indexposition + 1
in the StringS
. - If
cuSecond < 0xDC00
orcuSecond > 0xDFFF
, then returnfirst
. - Let
second
be the code unit at indexposition + 1
in the stringS
. - Let
cp
be(first – 0xD800) × 0x400 + (second – 0xDC00) + 0x10000
. - Return the elements of the UTF-16 Encoding (clause 6) of
cp
.
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.
In a browser:
<script src="at.js"></script>
Via npm:
npm install string.prototype.at
Then, in Node.js:
require('string.prototype.at');
// On Windows and on Mac systems with default settings, case doesn’t matter,
// which allows you to do this instead:
require('String.prototype.at');
Polyfills and test suites for String.fromCodePoint
, String.prototype.codePointAt
are available, too.
Mathias Bynens |
This polyfill is available under the MIT license.