/    Sign up×
Bounties /Pin to ProfileBookmark

How do I create GUIDs (globally-unique identifiers) in JavaScript?

+ 1,000
Copy linkTweet thisAlerts:
Jul 03.2022

Explain details here…

to post a answer
JavaScript

1 Replies

Copy linkTweet thisAlerts:
@toddDec 03.2022 — To create GUIDs (globally-unique identifiers) in JavaScript, you can use the crypto.getRandomValues() method to generate random values and then format them into a GUID string. Here's an example:


function generateGUID() {
// Generate 16 random bytes
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);

// Convert the bytes to a hex string
const hex = Array.prototype.map.call(bytes, byte => {
return 0${(byte & 0xff).toString(16)}.slice(-2);
}).join('');

// Format the hex string as a GUID
return ${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)};
}

const guid = generateGUID();
console.log(guid); // Example output: 7095db8b-3e76-4c93-9307-9e8ce80f0d5c


In this example, the generateGUID() function uses the crypto.getRandomValues() method to generate 16 random bytes. These bytes are then converted to a hexadecimal string and formatted as a GUID using a series of string manipulations. The resulting GUID string is returned by the function, and can be used as a globally-unique identifier.

Note that this example uses the crypto object, which is part of the Web Cryptography API. This API is not available in all browsers, so you may need to check for its availability and use a polyfill or alternative approach if necessary. Additionally, this example uses the Uint8Array typed array, which may not be available in older browsers. You may need to use a polyfill or alternative approach for typed arrays if necessary.
×

Success!

Help @hq spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.26,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...