Introduction
In this lab, we will explore how to generate a UUID in a browser using JavaScript. A UUID (Universally Unique Identifier) is a 128-bit value used to identify resources in a system in a way that is both unique and universal. By the end of this lab, you will have a clear understanding of how to generate a compliant UUID that can be used in your web applications.
Generate UUID in Browser
To generate a UUID compliant with RFC4122 version 4 in a browser, follow these steps:
- Open the Terminal/SSH and type
node. - Use the
Crypto.getRandomValues()method to generate a UUID. - Convert the UUID to a hexadecimal string using the
Number.prototype.toString()method. - Implement the following code:
const UUIDGeneratorBrowser = () =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
(
c ^
(crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
).toString(16)
);
- Call the
UUIDGeneratorBrowser()function to generate a UUID. For example,UUIDGeneratorBrowser()would return'7982fcfe-5721-4632-bede-6000885be57d'.
Summary
Congratulations! You have completed the Generate UUID (Browser) lab. You can practice more labs in LabEx to improve your skills.