I have a string, which always has a lenght of 32:
var str = "34v188d9cefa401f988563fb153xy04b";
Now I need to add a minus (-) after following number of characters:
- First minus after 8th character
- Second minus after 12th character
- Third minus after 16th character
- Fourth minus after 20th character
Output should be:
34v188d9-cefa-401f-9885-63fb153xy04b
So far I have tried different calculations with e.g.:
str.split('').reduce((a, b, c) => a + b + (c % 6 === 4 ? '-' : ''), '');
But I don’t get the expected result.
>Solution :
You could use a regex replacement:
var str = "34v188d9cefa401f988563fb153xy04b";
var output = str.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, "$1-$2-$3-$4-$5");
console.log(output);