Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uniqid() in javascript/jquery?

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)

like image 590
Alex Avatar asked Feb 02 '11 08:02

Alex


People also ask

How to generate unique id php?

The uniqid() function in PHP is an inbuilt function which is used to generate a unique ID based on the current time in microseconds (micro time). The ID generated from the uniqid() function is not optimal since it is based on the system time and is not cryptographically secured.

What is uniqid() in laravel?

The uniqid() function generates a unique ID based on the microtime (the current time in microseconds).

What is uid in php?

An UID is a unique identifier that will not change over time while a message sequence number may change whenever the content of the mailbox changes. This function is the inverse of imap_msgno().


2 Answers

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)}`:""}`;
};
like image 82
Josh Merlino Avatar answered Oct 25 '22 16:10

Josh Merlino


function uniqId(prefix) {
    if (window.performance) {
        var s = performance.timing.navigationStart;
        var n = performance.now();
        var base = Math.floor((s + Math.floor(n))/1000);
    } else {
        var n = new Date().getTime();
        var base = Math.floor(n/1000);
    }   
    var ext = Math.floor(n%1000*1000);
    var now = ("00000000"+base.toString(16)).slice(-8)+("000000"+ext.toString(16)).slice(-5);
    if (now <= window.my_las_uid) {
        now = (parseInt(window.my_las_uid?window.my_las_uid:now, 16)+1).toString(16);
    }
    window.my_las_uid = now;
    return (prefix?prefix:'')+now;
}

it is generated on "the same" priciple as PHP's uniqId() - specifically encoded time in microseconds.

like image 39
kobliha Avatar answered Oct 25 '22 15:10

kobliha