uniqid() in javascript/jquery?

All answers here (except phpjs) don't generate unique IDs because it's based on random. Random is not unique !

a simple solution :

window.unique_id_counter = 0 ;
var uniqid = function(){
    var id ;
    while(true){
        window.unique_id_counter++ ;
        id = 'uids_myproject_' + window.unique_id_counter ;
        if(!document.getElementById(id)){
            /*you can remove the loop and getElementById check if you 
              are sure that noone use your prefix and ids with this 
              prefix are only generated with this function.*/
            return id ;
        }
    }
}

It's easy to add dynamic prefix if it's needed. Just change unique_id_counter into an array storing counters for each prefixes.


Try this (Work in php).

$prefix = chr(rand(97,121));  
$uniqid =  $prefix.uniqid(); // $uniqid = uniqid($prefix);

Try this for JavaScript::

var n = Math.floor(Math.random() * 11);
var k = Math.floor(Math.random() * 1000000);
var m = String.fromCharCode(n) + k;

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)}`:""}`;
};