npm.io
1.1.0 • Published 1 month ago

identifier-regex

Licence
MIT
Version
1.1.0
Deps
1
Size
6 kB
Vulns
0
Weekly
0
Stars
18

identifier-regex

Regular expression for matching valid JavaScript identifiers

Install

npm install identifier-regex

Usage

import identifierRegex from 'identifier-regex';

identifierRegex().test('foo');
//=> true

identifierRegex().test('1kg');
//=> false

identifierRegex().test('await'); // Reserved identifier
//=> false

'@x $x #x'.match(identifierRegex({exact: false}));
//=> ['$x']

If you run the regex against untrusted user input in a server context, you should give it a timeout. I do not consider ReDoS a valid vulnerability for this package.

Although globalThis, Infinity, NaN, and undefined are properties of the global object and not identifiers, they are not matched by the regex because they should generally not be used as identifiers.

API

identifierRegex(options?)

Returns a RegExp for matching valid JavaScript identifiers.

options

Type: object

exact

Type: boolean
Default: true

Only match an exact string.

checkReserved

Type: boolean
Default: true

Reject reserved words and global properties like if, await, and undefined.

These are valid identifier syntax but should not be used as variable names, so they are rejected by default. Disable this when you only care about the syntax, such as for property keys ({if: 1}) or dot notation (foo.for), where they are allowed.

import identifierRegex from 'identifier-regex';

identifierRegex({checkReserved: false}).test('for');
//=> true
  • is-identifier - Check if a string is a valid JavaScript identifier

Keywords