How to convert UUID to String and vice versa in javascript
- Admin
- Sep 20, 2023
- Javascript
Sometimes, We need to convert UUID to string and string to UUID in dealing with Database’s unique identifier.
UUID is a Universal unique identifier that represents a unique string based on version 1,2,3,4,5.
UUID is a group of 32 hexadecimal strings with a format of 8-4-4-4-12 characters.
You can read more at javascript uuid
This tutorial explains multiple ways to Convert UUID to String and String to UUID
How to convert UUID to String in vanilla javascript?
UUID object has a fromString method which returns the string version. Call the toString method to return the string from a given UUID
here is an examples
var uuidData = Uuid.fromString("8336b1c6-59e7-4ac7-a0f6-0a80a38ef6a6");
var uuidString = uuidData.toString();
It works on all browsers in and simple way.
How to convert String to UUID in vanilla javascript?
There is no direct way to convert a string to UUID.
Multiple ways we can convert string to uuid in plain javascript
-
Using regular expressions
-
Create a Regular Expression that matches a string of acceptable characters and replaces the character at 8,12,16,18
Replace the string character at Position with a hyphen.
const uuidstring = "8336b1c659e74ac7a0f60a80a38ef6a6";
const uuid = uuidstring.replace(
/(.{8})(.{5})(.{5})(.{5})(.{12})/g,
"$1-$2-$3-$4-$5",
);
console.log(uuid);
8336b1c6-59e7-4ac7-a0f6-0a80a38ef6a6
- Another way using the slice string function
Create an array to hold the substring. First, Create a slice of a string for the first 8 characters and add it to the array Repeat slice logic for every 4 characters three times, pushes to array Finally, create a slice of string for the remaining 12 characters
Now, the Array contains a slice of substrings, Join these elements using a hyphen and return the string
const uuidstring = "8336b1c659e74ac7a0f60a80a38ef6a6";
var output = [];
output.push(uuidstring.slice(0, 8));
output.push(uuidstring.slice(8, 12));
output.push(uuidstring.slice(12, 16));
output.push(uuidstring.slice(16, 20));
output.push(uuidstring.slice(20, 32));
var guidOutput = output.join("-");
console.log(guidOutput);
Conclusion
Multiple approaches are specified here, To sum up, you can take whichever approach fits your application.