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)
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.
The uniqid() function generates a unique ID based on the microtime (the current time in microseconds).
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().
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)}`:""}`;
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With