Generate Unique IDs Like Youtube In JavaScript – Hashids

Category: Javascript , Recommended | May 24, 2023
Author:niieani
Views Total:91 views
Official Page:Go to website
Last Update:May 24, 2023
License:MIT

Preview:

Generate Unique IDs Like Youtube In JavaScript – Hashids

Description:

Hashids is an ID generator & number encoder that converts numeric values (or hex values) into Youtube video ID like unique IDs.

How to use it:

Install the Hashids package.

# NPM
$ npm install hashids --save

Import the Hashids module.

import Hashids from './lib/hashids.js'

Initialize the Hashids.

var myHashId = new Hashids();

Encode a number or hex.

// Mj3
hashids.encode(123);
// LPj9LA
hashids.encodeHex('fafafa');

Decode the generated IDs.

hashids.decode(id);
hashids.decodeHex(id);

Config the library by passing the following parameters:

  • salt: defaults to ”
  • minLength: defaults to 0
  • alphabet: defaults to ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890’
// Hashids(salt, minLength, alphabet)
var myHashId = new Hashids(0, 5, 'abc');

Check if is valid.

hashids.isValidId(id);

Changelog:

v2.3.0 (05/24/2023)

  • parse numeric strings as BigInt on supported systems

v2.2.11 (02/16/2023)

  • add “.js” extension to type definition import

v2.2.10 (11/20/2021)

  • Bugfix

v2.2.9 (11/07/2021)

  • Bugfix

v2.2.8 (12/18/2020)

  • Bugfix

v2.2.3 (12/12/2020)

  • Fixed: drop browser exports condition

v2.1.0 (11/10/2019)

  • protect from an infinite loop by validating IDs
  • add a public method hashids.isValidId(id) that validates the ID

You Might Be Interested In:


Leave a Reply