Convert to Valid JavaScript Identifier

1.0.0 · active · verified Sun Apr 19

The `to-valid-identifier` package provides a robust and minimalist utility to convert any given string into a syntactically valid JavaScript identifier. It ensures that the resulting identifier is unique for different inputs, effectively handling special characters, reserved keywords, and numbers. The current stable version is `1.0.0`. Maintained by Sindre Sorhus, this package adheres to best practices, ships with TypeScript types, and aims for high stability with infrequent but impactful major releases. Its core differentiator lies in its guarantee of unique identifiers, making it suitable for code generation, transpilation targets, and dynamic variable/property naming where collisions or invalid syntax are critical concerns.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to import and use `toValidIdentifier` to convert various strings into valid JavaScript identifiers, showcasing its handling of special characters, reserved words, and ensuring consistent output for identical inputs.

import toValidIdentifier from 'to-valid-identifier';

// Basic conversion
console.log(toValidIdentifier('hello world')); // => 'hello$j$world'

// Handles hyphens and special characters
console.log(toValidIdentifier('my-variable-name!')); // => 'my$j$variable$j$name$a$'

// Ensures uniqueness, even for reserved words or problematic starts
console.log(toValidIdentifier('undefined')); // => '$_undefined$'
console.log(toValidIdentifier('123abc')); // => '$123abc$'

// Demonstrates consistent output for specific inputs
const input1 = 'foo-bar';
const input2 = 'foo bar';
const input3 = 'foo-bar'; // Same input, same output

console.log(`'${input1}' => ${toValidIdentifier(input1)}`);
console.log(`'${input2}' => ${toValidIdentifier(input2)}`);
console.log(`'${input3}' => ${toValidIdentifier(input3)}`);

view raw JSON →