Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript: Insert a character after every N characters

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading