to-valid-identifier
Convert a string to a valid JavaScript identifier
Last updated 6 months ago by sindresorhus .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install to-valid-identifier 
SYNC missed versions from official npm registry.

to-valid-identifier

Convert a string to a valid JavaScript identifier

Install

npm install to-valid-identifier

Usage

import toValidIdentifier from 'to-valid-identifier';

toValidIdentifier('foo');
//=> 'foo'

toValidIdentifier('foo-bar');
//=> 'foo$j$bar'

toValidIdentifier('$');
//=> '$a$'

toValidIdentifier('undefined');
//=> '$_undefined$'

API

toValidIdentifier(string)

Convert the given string to a valid JavaScript identifier.

Different inputs will always generate unique identifiers.

Use cases

  • Code Generation: Automate safe variable naming in scripts, avoiding syntax errors from invalid characters.
  • Compilers/Transpilers: Essential for non-JavaScript languages compiling to JavaScript, ensuring that identifiers are compliant.
  • Dynamic Function Names: Generate unique and valid function names from dynamic content such as user inputs or database fields.
  • API Wrappers: Convert API response properties into valid JavaScript object keys for easier access.
  • Template Processing: Ensure template placeholders are converted to valid JavaScript identifiers when replaced with dynamic values.

Related

  • is-identifier - Check if a string is a valid JavaScript identifier

Current Tags

  • 1.0.0                                ...           latest (6 months ago)

3 Versions

  • 1.0.0                                ...           6 months ago
  • 0.1.1                                ...           2 years ago
  • 0.1.0                                ...           2 years ago
Maintainers (1)
Downloads
Today 0
This Week 0
This Month 0
Last Day 0
Last Week 0
Last Month 0
Dependencies (2)
Dev Dependencies (2)
Dependents (1)

Copyright 2013 - present © cnpmjs.org | Home |