Search code examples
javascriptnode.jsuuid

How to convert strings to UUID v4 in NodeJs?


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!!


Solution

  • 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)