Skip to content Skip to sidebar Skip to footer

Javascript String To Guid

in javascript, what is the easiest way to convert this string 798205486e954fa880a0b366e6725f71 to GUID format like this 79820548-6e95-4fa8-80a0-b366e6725f71 this is the messy way

Solution 1:

Cleanest way?

Shortest:

var txt = shift.employee.id;
txt.replace(/([0-z]{8})([0-z]{4})([0-z]{4})([0-z]{4})([0-z]{12})/,"$1-$2-$3-$4-$5");
//"79820548-6e95-4fa8-80a0-b366e6725f71"

or if you don't care about the acceptable characters, it can be be even shorter (and cleaner):

txt.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5");  //boom!

Some don't like using regex for everything, but I liked it.

Solution 2:

I did it in string manipulation

var str = "798205486e954fa880a0b366e6725f71";
var parts = [];
parts.push(str.slice(0,8));
parts.push(str.slice(8,12));
parts.push(str.slice(12,16));
parts.push(str.slice(16,20));
parts.push(str.slice(20,32));
var GUID = parts.join('-'); 

console.log(GUID) // prints expected GUID

I did it this way because I don't like inserting characters between strings. If there is any problem tell me.

Or you could use a for loop like bellow

var str = "798205486e954fa880a0b366e6725f71";
var lengths = [8,4,4,4,12];
var parts = [];
varrange = 0; 
for (var i = 0; i < lengths.length; i++) {
    parts.push(str.slice(range,range+lengths[i]));
    range += lengths[i];
};
var GUID = parts.join('-');
console.log(GUID);

Solution 3:

You could use an regular expression:

var rxGetGuidGroups =/(\w{8})(\w{4})(\w{4})(\w{4})(\w{12})/,
    employeeId = shift.employee.id.replace(rxGetGuidGroups, '$1-$2-$3-$4-$5');

jsFiddle

Solution 4:

Try this function, It will return string in GUID format

function getGuid(str){
returnstr.slice(0,8)+"-"+str.slice(8,12)+"-"+str.slice(12,16)+
"-"+str.slice(16,20)+"-"+str.slice(20,str.length+1)
}

Solution 5:

Or you would try-

var guid = (function () {
    functions4() {
        returnMath.floor((1 + Math.random()) * 0x10000)
               .toString(16)
               .substring(1);
    }
    returnfunction () {
        returns4() + s4() + '-' + s4() + '-' + s4() + '-' +
           s4() + '-' + s4() + s4() + s4();
    };
})();

Where Your new guid be like-

var newGuid= guid();

newGuid returns- 7d4b3ef0-b5bb-5c42-2a02-80a4371babf8

Post a Comment for "Javascript String To Guid"