Note: This proposal was not upstreamed into the ECMAScript specification! This repository is kept for historical purposes. Years later, in November 2020, a distinct proposal adds String.prototype.at
with different semantics.
String.prototype.at
polyfill
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
Spec proposal forString.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:
O
be RequireObjectCoercible(this value)
.S
be ToString(O)
.ReturnIfAbrupt(S)
.position
be ToInteger(pos)
.ReturnIfAbrupt(position)
.size
be the number of elements in S
.position < 0
or position ≥ size
, return the empty String.first
be the code unit at index position
in the String S
.cuFirst
be the code unit value of the element at index 0
in the String first
.cuFirst < 0xD800
or cuFirst > 0xDBFF
or position + 1 = size
, then return first
.cuSecond
be the code unit value of the element at index position + 1
in the String S
.cuSecond < 0xDC00
or cuSecond > 0xDFFF
, then return first
.second
be the code unit at index position + 1
in the string S
.cp
be (first – 0xD800) × 0x400 + (second – 0xDC00) + 0x10000
.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.
This polyfill is available under the MIT license.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4