How to generate short uid like “aX4j9Z” (in JS)

2019-01-30 10:29发布

For my web application (in JavaScript) I want to generate short guids (for different objects - that are actually different types - strings and arrays of strings)

I want something like "aX4j9Z" for my uids (guids).

So these uids should be lightweight enough for web transfer and js string processing and quite unique for not a huge structure (not more than 10k elements). By saying "quite unique" I mean that after the generation of the uid I could check whether this uid does already exist in the structure and regenerate it if it does.

7条回答
再贱就再见
2楼-- · 2019-01-30 11:19

There is also an awsome npm package for this : shortid

Amazingly short non-sequential url-friendly unique id generator.

ShortId creates amazingly short non-sequential url-friendly unique ids. Perfect for url shorteners, MongoDB and Redis ids, and any other id users might see.

  • By default 7-14 url-friendly characters: A-Z, a-z, 0-9, _-
  • Non-sequential so they are not predictable.
  • Supports cluster (automatically), custom seeds, custom alphabet.
  • Can generate any number of ids without duplicates, even millions per day.
  • Perfect for games, especially if you are concerned about cheating so you don't want an easily guessable id.
  • Apps can be restarted any number of times without any chance of repeating an id.
  • Popular replacement for Mongo ID/Mongoose ID.
  • Works in Node, io.js, and web browsers.
  • Includes Mocha tests.

Usage

var shortid = require('shortid');
console.log(shortid.generate()); //PPBqWA9
查看更多
登录 后发表回答