Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add colon (:) after every 2nd character using Javascript

I have a string and want to add a colon after every 2nd character (but not after the last set), eg:

12345678

becomes

12:34:56:78

I've been using .replace(), eg:

mystring = mystring.replace(/(.{2})/g, NOT SURE WHAT GOES HERE)

but none of the regex for : I've used work and I havent been able to find anything useful on Google.

Can anyone point me in the right direction?

like image 862
MeltingDog Avatar asked Dec 15 '15 03:12

MeltingDog


1 Answers

mystring = mystring.replace(/(..)/g, '$1:').slice(0,-1)

This is what comes to mind immediately. I just strip off the final character to get rid of the colon at the end.

If you want to use this for odd length strings as well, you just need to make the second character optional. Like so:

mystring = mystring.replace(/(..?)/g, '$1:').slice(0,-1)
like image 155
Cereal Avatar answered Oct 01 '22 20:10

Cereal