Let's say I got a string below:
const input = '83e54feeeb444c7484b3c7a81b5ba2fd';
My ideal output is an uuid v4:
83e54fee-eb44-4c74-84b3-c7a81b5ba2fd
About the solution, I only come up with the idea:
function insertString(str, index, value) {
return str.substr(0, index) value str.substr(index);
}
function converToUUID(_uuid){
_uuid = insertString(_uuid, 8, '-')
_uuid = insertString(_uuid, 13, '-')
_uuid = insertString(_uuid, 18, '-')
_uuid = insertString(_uuid, 23, '-')
return _uuid
}
console.log(converToUUID(a))
Is there a way to get the ideal output by not keep calling the insertString
function?
Thanks for any help!!
CodePudding user response:
I would use a regex
const input = '83e54feeeb444c7484b3c7a81b5ba2fd';
const output = input.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/g, '$1-$2-$3-$4-$5')
console.log(output)
CodePudding user response:
const uuidRx = new RegExp(/([a-zA-Z0-9]{8})([a-zA-Z0-9]{4})([a-zA-Z0-9]{4})([a-zA-Z0-9]{5})([a-zA-Z0-9]{11})/);
const str = "83e54feeeb444c7484b3c7a81b5ba2fd";
const uuid = str.replace(uuidRx, "$1-$2-$3-$4-$5");
console.log(uuid);