A JavaScript prollyfill for the proposed String.isIdentifierStart
and String.isIdentifierPart
methods, based on the October 10, 2013 draft of the strawman.
Feel free to fork if you see possible improvements!
In a browser:
<script src="https://github.com/mathiasbynens/identifier-identification/raw/master/identifier.js"></script>
Via npm:
npm install identifier-identification
Then, in Node.js:
require('identifier-identification');
// Is U+0B83 a valid `IdentifierStart` code point as per ECMAScript 3?
String.isIdentifierStart(0x0B83, 3);
// → false
// What about ECMASCript 5?
String.isIdentifierStart(0x0B83, 5);
// → false
// Ok, and in ECMAScript 6?
String.isIdentifierStart(0x0B83, 6);
// → true
// Is U+2FA1D a valid `IdentifierPart` code point as per ECMAScript 3?
String.isIdentifierPart(0x2FA1D, 3);
// → false
// What about ECMASCript 5?
String.isIdentifierPart(0x2FA1D, 5);
// → false
// Ok, and in ECMAScript 6?
String.isIdentifierPart(0x2FA1D, 6);
// → true
In order to make this polyfill ES3/ES5-compatible, this script includes a String.prototype.codePointAt
polyfill.
If the second, optional, edition
parameter is omitted, String.isIdentifierStart
and String.isIdentifierPart
are supposed to return true
if the current engine supports it as such, and false
otherwise (as per the proposal in the strawman). Because this is a polyfill for use in older ECMAScript environments, I’ve decided to use the ECMAScript 6 definition for identifiers and the latest available Unicode version data to determine the result instead. In a proper ES6 environment, String.isIdentifierPart(0x2FA1D)
is always true
— without violating the strawman, this polyfill could never return that result in a non-ES6 environment, which didn’t seem very useful.
Mathias Bynens |
This polyfill is available under the MIT license.