To check if a string is a valid UUID (or a Universally unique identifier), we can use a special regex expression to check that in JavaScript.
TL;DR
// Regular expression to check if string is a valid UUID
const regexExp = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi;
// String with valid UUID separated by dash
const str = "a24a6ea4-ce75-4665-a070-57453082c256";
regexExp.test(str); // true
A valid UUID should have 5
sections separated by a dash (-
) and in the first section it should have 8
characters, the second, third, and the fourth section should have 4
characters each, and the last section should have 12
characters with a total of 32
characters.
All 5 sections should have characters either of the range from number 0 to 9
, small alphabets a to f
or capital alphabets A to F
.
For an example, a valid UUID may look like this,
a24a6ea4-ce75-4665-a070-57453082c256
# 8 4 4 4 12 characters = 32 total characters
So to check if a string is valid UUID we can use this regular expression,
// Regular expression to check if string is a valid UUID
const regexExp = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi;
This matches all the valid UUID since it checks for the above test cases.
Now let's write a string with valid UUID like this,
// Regular expression to check if string is a valid UUID
const regexExp = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi;
// String with valid UUID separated by dash
const str = "a24a6ea4-ce75-4665-a070-57453082c256";
Now to test the string, we can use the test()
method available in the regular expression we defined. It can be done like this,
// Regular expression to check if string is a valid UUID
const regexExp = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi;
// String with valid UUID separated by dash
const str = "a24a6ea4-ce75-4665-a070-57453082c256";
regexExp.test(str); // true
- The
test()
method will accept astring
type as an argument to test for a match. - The method will return boolean
true
if there is a match using the regular expression andfalse
if not.
See the above example live in JSBin.
If you want this as a utility function which you can reuse, here it is,
/* Check if string is valid UUID */
function checkIfValidUUID(str) {
// Regular expression to check if string is a valid UUID
const regexExp = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi;
return regexExp.test(str);
}
// Use the function
checkIfValidUUID("a24a6ea4-ce75-4665-a070-57453082c256"); // true
checkIfValidUUID("a24a6ea4-ce75-4665-a070"); // false
That's all! 😃