Generate Guid or UUID
So, how do we generate a Guid or UUID in TypeScript and Angular? C# is kind enough to provide us a built-in, but in Angular, we have to install the package!
If we do not want to install anything and quickly just generate a random Guid then we can simply do this:
generateGUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
This will return a Guid as a string 👌
Now let's do the reverse... let's check if the string is a Guid:
isStringGuid(guidAsString: stirng){
const guidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
if (guidRegex.test(guidAsString)) {
console.log(`${guidAsString} is Guid`);
}
else {
//Handle the case when it is not a GUID
console.log("Nope! It is not!");
}
}
Â
No files yet, migration hasn't completed yet!