uniqid() in javascript/jquery?

Alex picture Alex · Feb 2, 2011 · Viewed 44k times · Source

what's the equivalent of this function in javascript:

http://php.net/manual/en/function.uniqid.php

Basically I need to generate a random ID that looks like: a4245f54345 and starts with a alphabetic character (so I can use it as a CSS id)

Answer

Josh Merlino picture Josh Merlino · Feb 3, 2018

I have been using this...

I use it exactly as I would if it where PHP. Both return the same result.

function uniqid(prefix = "", random = false) {
    const sec = Date.now() * 1000 + Math.random() * 1000;
    const id = sec.toString(16).replace(/\./g, "").padEnd(14, "0");
    return `${prefix}${id}${random ? `.${Math.trunc(Math.random() * 100000000)}`:""}`;
};