Safe Identifier String Sanitization

0.4.2 · active · verified Sun Apr 19

safe-identifier is a focused utility library designed to sanitize arbitrary strings for safe use as JavaScript identifiers and object property names. It currently stands at version 0.4.2 and has shown an active release cadence, with several minor versions released recently. The library's core functionality includes replacing invalid characters with underscores, pre-pending an underscore if the resulting identifier conflicts with a JavaScript reserved word (covering ES3 to ES2018 and active proposals), and optionally appending a unique hash to generated identifiers. For property names, it intelligently uses dot notation (`obj.key`) or bracket notation (`obj["key"]`) based on key validity and ECMAScript 3rd Edition reserved words, ensuring compatibility down to IE8. Its primary differentiator is its comprehensive standard coverage and explicit handling for browser compatibility and uniqueness.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic usage of `identifier` for sanitizing string keys to be valid JavaScript identifiers, including handling reserved words and generating unique hashes, and `property` for generating safe object property accessors with ES3 compatibility.

import { identifier, property } from 'safe-identifier';

// Basic identifier sanitization
console.log(`'Foo' -> ${identifier('Foo')}`); // 'Foo'
console.log(`'enum' (reserved word) -> ${identifier('enum')}`); // '_enum'

// Identifier with uniqueness hash
const keyWithSpaces = 'my var';
const uniqueId1 = identifier(keyWithSpaces, true);
const uniqueId2 = identifier(' another\tkey ', true);
console.log(`'${keyWithSpaces}' (unique) -> ${uniqueId1}`); // Example: 'my_var_hk17pp'
console.log(`' another\tkey ' (unique) -> ${uniqueId2}`); // Example: 'another_key_1d8fi3'

// Property name sanitization
console.log(`'Foo', 'bar' -> ${property('Foo', 'bar')}`); // 'Foo.bar'
console.log(`'Foo', 'bar\nbar' -> ${property('Foo', 'bar\nbar')}`); // 'Foo["bar\nbar"]'
console.log(`null, 'foo' -> ${property(null, 'foo')}`); // 'foo'
console.log(`null, 'void' (ES3 reserved) -> ${property(null, 'void')}`); // '"void"' (quoted for ES3 compatibility)

view raw JSON →