JavaScript Identifier Regular Expression
The `identifier-regex` package provides a precise regular expression function, `identifierRegex()`, designed to match valid JavaScript identifiers according to the ECMAScript specification. This includes proper handling of reserved words and specific syntax rules. The current stable version is 1.0.1, focusing on correctness and stability rather than rapid feature additions. Its primary differentiator is its strict adherence to JavaScript identifier rules, offering an `exact` option to control whether the regex matches the entire string or finds identifiers within a larger text. It explicitly excludes global properties like `Infinity` from being considered valid identifiers, aligning with common usage expectations. This library is ideal for parsers, linters, or any application needing to validate or extract JavaScript identifiers reliably.
Common errors
-
TypeError: identifierRegex is not a function
cause Attempting to use the `identifierRegex` function directly as a `RegExp` object without calling it first (e.g., `identifierRegex.test('foo')`). The function returns a RegExp instance.fixCall `identifierRegex()` to obtain the regular expression object: `identifierRegex().test('foo')`. -
SyntaxError: Cannot use import statement outside a module
cause Attempting to use ES module `import` syntax in a CommonJS (CJS) environment without proper configuration (e.g., without `'type': 'module'` in `package.json` for Node.js).fixEnsure your project is configured as an ES module by adding `'type': 'module'` to your `package.json`, or use a bundler that transpiles ES modules to CJS for older environments. This package requires Node.js >=18, which has robust ESM support. -
My regex isn't matching anything in a longer string (e.g., 'foo bar').
cause The default `exact` option is `true`, meaning the regex tries to match the entire input string. `'foo bar'` is not a single, exact identifier.fixSet the `exact` option to `false` when you want to find identifiers within a larger string: `identifierRegex({ exact: false }).test('foo bar')`.
Warnings
- gotcha When running the regex against untrusted user input in a server context, it is strongly recommended to give the regex a timeout (e.g., using `super-regex`) to prevent potential Regular Expression Denial of Service (ReDoS) attacks. While the package maintainer does not consider ReDoS a direct vulnerability for this specific package, it's a critical security consideration for user-facing applications.
- gotcha The regex will NOT match properties of the global object like `globalThis`, `Infinity`, `NaN`, and `undefined` as valid identifiers. While these are JavaScript built-ins, the library's design choice is to exclude them from identifier matching, which might surprise users expecting a broader match.
- gotcha The default `exact` option for `identifierRegex()` is `true`. This means the regex will only match if the entire input string is a valid JavaScript identifier. If you intend to find or extract identifiers from within a larger string (e.g., `'foo bar'.match(identifierRegex())`), you must explicitly set `{ exact: false }`.
Install
-
npm install identifier-regex -
yarn add identifier-regex -
pnpm add identifier-regex
Imports
- identifierRegex
const identifierRegex = require('identifier-regex');import identifierRegex from 'identifier-regex';
- RegExp instance
identifierRegex.test('foo');const myIdentifierRegex = identifierRegex();
- identifierRegex with options
import { identifierRegex } from 'identifier-regex';import identifierRegex from 'identifier-regex'; const looseRegex = identifierRegex({ exact: false });
Quickstart
import identifierRegex from 'identifier-regex';
// Basic usage: testing if a string is a valid identifier
console.log("Is 'foo' a valid identifier?", identifierRegex().test('foo'));
//=> true
console.log("Is '1kg' a valid identifier?", identifierRegex().test('1kg'));
//=> false (Identifiers cannot start with a number)
console.log("Is 'await' a valid identifier?", identifierRegex().test('await'));
//=> false (Reserved word)
// Using 'exact: false' to find identifiers within a larger string
const textWithIdentifiers = 'function _myVar_($param1) { const $var2 = 1; }';
const identifiersInText = textWithIdentifiers.match(identifierRegex({ exact: false, global: true }));
console.log(`Identifiers found in "${textWithIdentifiers}":`, identifiersInText);
//=> ['_myVar_', '$param1', '$var2']
// Demonstrate that calling identifierRegex() returns a RegExp instance
const myRegexInstance = identifierRegex();
console.log('Type of returned value:', typeof myRegexInstance);
console.log('Is it a RegExp instance?', myRegexInstance instanceof RegExp);