uniqid() in javascript/jquery?
Asked Answered
J

8

16

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)

Jota answered 2/2, 2011 at 8:51 Comment(2)
I'm not going to close this as a duplicate, as php's uniqid doesn't seem to create GUID's (although that's what you would expect from it), but perhaps you can still find some help here: #105534Medford
Do you need it to be random, or can you simply use a sequential counter? i.e. 'a1', 'a2', etc...Tace
T
10

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;
Twelvetone answered 2/2, 2011 at 9:3 Comment(3)
The question is asking for a JavaScript function.Balfore
This Java-script code is not have accuracy(not sure always getting alphabetic ). but you can do some change in code according your requirements.Twelvetone
This is not unique hence not equivalent of php uniqid functionConfessional
B
36

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)}`:""}`;
};
Barrybarrymore answered 3/2, 2018 at 2:49 Comment(3)
Perfect solution, exactly as OP asked. This should be the accepted answer.Thuggee
What are arguments a and b for?Werbel
argument a is a a prefix and argument b will add a random number at the end to help avoid collision.Barrybarrymore
T
10

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;
Twelvetone answered 2/2, 2011 at 9:3 Comment(3)
The question is asking for a JavaScript function.Balfore
This Java-script code is not have accuracy(not sure always getting alphabetic ). but you can do some change in code according your requirements.Twelvetone
This is not unique hence not equivalent of php uniqid functionConfessional
A
6

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.

Antonyantonym answered 13/5, 2015 at 12:56 Comment(0)
H
3
<html>
<head>
<script type="text/javascript">
function generateSerial(len) {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var string_length = 10;
    var randomstring = '';

    for (var x=0;x<string_length;x++) {

        var letterOrNumber = Math.floor(Math.random() * 2);
        if (letterOrNumber == 0) {
            var newNum = Math.floor(Math.random() * 9);
            randomstring += newNum;
        } else {
            var rnum = Math.floor(Math.random() * chars.length);
            randomstring += chars.substring(rnum,rnum+1);
        }

    }
    alert(randomstring);
}
generateSerial(8);
</script>
</head>
<body>

</body>
</html>

It's a bit convoluted, but you get the gist I'm sure!
Example: http://jsfiddle.net/Ng4tB/

Hinder answered 2/2, 2011 at 9:55 Comment(0)
H
2

The real question is, do you need the UUID to be RFC 4122 compliant? Your question seems to suggest you don't, so it wouldn't be too hard to create a function based simply on Math.random() to generate IDs like that. Plus it will be a lot faster than the phpJS implementation.

Houghton answered 2/2, 2011 at 9:0 Comment(2)
but what is RFC 4122 compliant?Jota
@DylannCordel: Fair point, but neither are any of the other strategies suggested here. The PHP uniqid() method is essentially equivalent to microtime(), and any purely algorithmic uuid generator that runs in a browser or on a (load balanced, multi-instance) web server is going to have the potential for collisions -- UNLESS namespaced-by-server (clearly not the asker's intention) or verified against a centralized guid service. His 1 letter + 10 alphanumerics scheme yields a space of 95 quintillion or roughly 56bits of entropy. I wouldn't worry too much about collisions.Houghton
S
1
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.

Standice answered 28/12, 2018 at 10:20 Comment(1)
Thanks! I wrote a test to compare your Javascript function with the output from PHP uniqid(). I found your answer to be more accurate.Stalinism
A
1

Underscore.js has a uniqueid() method
https://underscorejs.org/#uniqueId

_.uniqueId([prefix])
Generate a globally-unique id for client-side models or DOM elements that need one. If prefix is passed, the id will be appended to it.

_.uniqueId('contact_');  
=> 'contact_104'
Anaximenes answered 4/4, 2019 at 18:6 Comment(0)
W
0

Found this:

https://github.com/makeable/uuid-v4.js/blob/master/uuid-v4.js

and slightly modified to this:

function uniqid(length){
  var dec2hex = [];
  for (var i=0; i<=15; i++) {
    dec2hex[i] = i.toString(16);
  }

  var uuid = '';
  for (var i=1; i<=36; i++) {
    if (i===9 || i===14 || i===19 || i===24) {
      uuid += '-';
    } else if (i===15) {
      uuid += 4;
    } else if (i===20) {
      uuid += dec2hex[(Math.random()*4|0 + 8)];
    } else {
      uuid += dec2hex[(Math.random()*16|0)];
    }
  }

  if(length) uuid = uuid.substring(0,length);
  return uuid;
}

works great.

Werbel answered 5/7, 2019 at 16:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.