Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
126
rated 0 times [  131] [ 5]  / answers: 1 / hits: 29574  / 10 Years ago, tue, august 5, 2014, 12:00:00

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 I do it :) im looking for the cleanest way



var employeeId = shift.employee.id.substring(0, 8) + - + shift.employee.id.substring(8, 12)
+ - + shift.employee.id.substring(12, 16) + - + shift.employee.id.substring(16, 20) + - + shift.employee.id.substring(20, 32);

More From » string

 Answers
23

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 = [];
var range = 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);

[#69910] Saturday, August 2, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
declanm

Total Points: 614
Total Questions: 105
Total Answers: 97

Location: Dominica
Member since Sat, Nov 5, 2022
2 Years ago
;