0

How to generate a valid UUID v4 that starts with specific characters?

Suppose I want to generate UUID v4 that starts with 00 – short of looping through random UUIDs until I get UUID that starts with 00, is there a better way of doing it?

Luc Gagan
  • 301
  • 9
  • find a UUIDv4 generator, modify it to your specs - or simply replace the first two characters with `00` - since a v4 UUID is purely random, this is perfectly valid to do – Jaromanda X May 22 '23 at 01:33
  • I presume you're aware, but doing this will increase [collision probability](https://stackoverflow.com/a/24876263/438273) (in a insignificant way, practically, of course) — it might be useful to simply prefix the full UUID if your string length isn't constrained — or just prefix a different UID schema (e.g. [`nanoid`](https://github.com/ai/nanoid#comparison-with-uuid)). – jsejcksn May 22 '23 at 02:59

1 Answers1

0

You can just remove the first two characters of a generated UUID and prepend "00" in its place.

console.log('00' + crypto.randomUUID().slice(2));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80