
isIdentifier is a tiny JavaScript utility that helps developers determine if a given string is a valid identifier in JavaScript.
It uses regular expressions to perform this check. If the provided string is a valid identifier, the library returns true; otherwise, it returns false.
Moreover, the library’s support for reserved identifiers adds an extra layer of protection. Reserved identifiers, like ‘await’ and ‘export’, are keywords in JavaScript and cannot be used as regular identifiers.
How to use it:
1. Install and import the isIdentifier with NPM:
npm install is-identifier
import isIdentifier from 'is-identifier';
2. Check your string by passing it to the isIdentifier function. Note that identifiers like ‘globalThis’, ‘Infinity’, ‘NaN’, and ‘undefined’, despite being global properties, are treated as reserved in this context. The library will flag them as invalid for use as identifiers to prevent common errors in code handling.
// => true
console.log(isIdentifier('cssscript'));
// => false
console.log(isIdentifier('cssscript.com'));
// => false
console.log(isIdentifier('delete'));3. Here is a list of all reserved identifiers recognized by isIdentifier.
// Keywords 'await', 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'enum', 'export', 'extends', 'false', 'finally', 'for', 'function', 'if', 'import', 'in', 'instanceof', 'new', 'null', 'return', 'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'var', 'void', 'while', 'with', 'yield', // Future reserved keywords 'implements', 'interface', 'package', 'private', 'protected', 'public', // Not keywords, but still restricted 'arguments', 'eval',
4. The regex used to check if a string is a valid JS identifier:
const baseRegex = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}]*/u;
const basePattern = `(?!${[...reservedIdentifiers({includeGlobalProperties: true})].join('|')})${baseRegex.source}`;
const regex = new RegExp(basePattern, 'u');
const regexExact = new RegExp(`^${basePattern}$`, 'u');Changelog:
v1.0.1 (07/12/2024)
- Remove incorrect TypeScript type guard







