Search code examples
javascriptuuidguid

Convert GUID to 8-4-4-4-12 format in javascript


I am looking to convert a GUID such as 18d874986a114520bd29466a446a50eb to the format 18d87498-6a11-4520-bd29-466a446a50eb

Is there a function in Javascript for doing this?

I googled a bit and looks like the 8-4-4-4-12 format is called UUID. I however, do not find any to UUID conversion libraries.

Do I need to write my own?


Solution

  • One simple approach uses a regex replacement:

    var uuid = "18d874986a114520bd29466a446a50eb";
    uuid = uuid.replace(/^([a-f0-9]{8})([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{12})$/i, "$1-$2-$3-$4-$5");
    console.log(uuid);