JavaScript Identifier Regular Expression

1.0.1 · active · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

Demonstrates importing the `identifierRegex` function, using it to test strings for identifier validity (including reserved words), and extracting identifiers from longer strings with the `exact: false` option, while also showing it returns a `RegExp` instance.

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);

view raw JSON →