Encode and decode UUIDs into URL-safe Base 64
// converts a UUID to a URL-safe version of base 64. | |
const encode = uuid => { | |
const stripped = uuid.replace(/-/g, ""); // remove dashes from uuid | |
const true64 = btoa( | |
String.fromCharCode.apply( | |
null, | |
stripped | |
.replace(/\r|\n/g, "") | |
.replace(/([\da-fA-F]{2}) ?/g, "0x$1 ") | |
.replace(/ +$/, "") | |
.split(" ") | |
) | |
); // turn uuid into base 64 | |
const url64 = true64.replace(/\//g, "_").replace(/\+/g, "-"); // replace non URL-safe characters | |
return url64; | |
}; | |
// takes a URL-safe version of base 64 and converts it back to a UUID. | |
const decode = url64 => { | |
const true64 = url64.replace(/_/g, "/").replace(/-/g, "+"); // replace url-safe characters with base 64 characters | |
const raw = atob(true64); // decode the raw base 64 into binary buffer. | |
let hex = ""; // create a string of length 0 | |
let hexChar; // mostly because you don't want to initialize a variable inside a loop. | |
for (let i = 0, l = raw.length; i < l; i++) { | |
hexChar = raw.charCodeAt(i).toString(16); // get the char code and turn it back into hex. | |
hex += hexChar.length === 2 ? hexChar : "0" + hexChar; // append hexChar as 2 character hex. | |
} | |
hex = hex.toLowerCase(); // standardize. | |
// pad zeroes at the front of the UUID. | |
while (hex.length < 32) { | |
hex = "0" + hex; | |
} | |
// add dashes for 8-4-4-4-12 representation | |
const uuid = hex.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, "$1-$2-$3-$4-$5"); | |
return uuid; | |
}; | |
const urlUuid = { encode, decode }; | |
export default urlUuid |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment