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
Code language: ReasonML (reasonml)
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)
isUUID Function
To create a function that checks if the provided value is a UUID, we can wrap the code above into a function:
function isUUID(value) {
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');
return regex.test(value);
}
Code language: JavaScript (javascript)
UUID Regex Detail
This regular expression uses the following rules:
- The
^
and$
characters are used to match the start and end of the string, respectively, ensuring that the entire string is matched and not just a substring. - The pattern is surrounded by square brackets (
[
and]
), which indicate a character class. This means that the regular expression will match any of the characters within the brackets. - The
0-9
anda-f
characters within the character class specify a range of characters. This means that the regular expression will match any digit from0
to9
, and any lowercase letter froma
tof
. - The
{n}
notation after each character class specifies a repetition count. This means that the regular expression will match exactlyn
occurrences of the character class. For example,{8}
means that the regular expression will match exactly eight characters from the character class. - The
-
character is included within the character class to match the hyphen character that separates the different sections of a UUID. - The
1-5
and89ab
characters within the character class are used to match specific patterns in the UUID. These patterns are match UUID versions 1-5.
Creating a UUID in JavaScript
In JavaScript, the crypto.randomUUID()
method generates a random Universal Unique Identifier (UUID) in the standard format.
A UUID is a unique identifier that is often used to identify records in a database, or to identify devices and other objects in a network.
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
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.
Leave a Reply