Best Way to Create a GUID/UUID in JavaScript

It used to be required to use a package or create your own function to generate a UUID in JavaScript.

But now the crypto.randomUUID() method can be used to generate a v4 UUID. This will work in Node.js and all major browsers.

Here’s an example of how to use the crypto.randomUUID() method in JavaScript:

// Generate a random UUID var uuid = crypto.randomUUID(); // Print the UUID to the console // Example output: 'd378a30e-3179-43b3-b118-de3d94d83908' console.log(uuid);
Code language: JavaScript (javascript)

Keep in mind that the crypto.randomUUID() method is not supported in all browsers, so you’ll need to check for browser compatibility before using it in your code.

If compatibility is a big concern, then you can use the uuid module:

npm install uuid

Example of how to generate a UUID using the uuid module:

import { v4 as uuidv4 } from 'uuid'; uuidv4();
Code language: JavaScript (javascript)

Check out the uuid Github page for more information.

How to Check if a Variable is a UUID

To match a UUID (also known as a universally unique identifier) using a regular expression in JavaScript, you can use the following regex pattern:

/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i

And here is an example using this regex in JavaScript:

const regex = new RegExp('^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$', 'i'); // Create a UUID using the crypto library // Example: '7a02a57e-1dbc-4219-83eb-c7d1c99865ac' let uuid = crypto.randomUUID(); // Test if the regex matches the UUID const matches = regex.test(uuid); // Prints: true console.log(matches);
Code language: JavaScript (javascript)

You can read our JavaScript UUID Regex article for more information.

References

https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID

https://github.com/uuidjs/uuid


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *