Home >Web Front-end >JS Tutorial >How Can I Generate GUIDs/UUIDs in JavaScript?
Creating GUIDs / UUIDs in JavaScript
Generating GUIDs (globally-unique identifiers) in JavaScript requires consideration of the limitations of built-in random number generators and the availability of browser APIs.
crypto.randomUUID()
For modern browsers and JS runtimes, crypto.randomUUID() provides a standardized and secure method of generating UUIDs. However, this method is only accessible when the page is served locally or over HTTPS.
uuid Module
For generating UUIDs of various versions, handling legacy platforms, or in non-secure contexts, the uuid module offers a robust and widely supported solution.
Alternative Method
In the absence of the above options, the following method generates RFC4122-compliant UUIDs:
function uuidv4() { return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, c => (+c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> +c / 4).toString(16) ); } console.log(uuidv4());
The above is the detailed content of How Can I Generate GUIDs/UUIDs in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!