Add a colon (:) after every 2nd character with Javascript

I have a line and you want to add a colon after every second character (but not after the last set), for example:

12345678

becomes

12: 34: 56: 78

I used .replace() , for example:

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

but none of the regular expressions for : I did not use the work, and I could not find anything useful on Google.

Can someone point me in the right direction?

+5
source share
9 answers
 mystring = mystring.replace(/(..)/g, '$1:').slice(0,-1) 

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

If you want to use this for odd-length strings, you just need to make the second character optional. For instance:

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

Without the need to remove any back colons:

 mystring = mystring.replace(/..\B/g, '$&:') 

\B matches the border of a non-word of zero width; in other words, when it falls to the end of a line, it will not match (since this is considered the word boundary) and therefore will not perform a replacement (hence, also the trailing colon).

$& contains a matched substring (so you don't need to use a capture group).

+5
source

If you are looking for an approach other than RegEx, try the following:

 var str = '12345678'; var output = ''; for(var i = 0; i < str.length; i++) { output += str.charAt(i); if(i % 2 == 1 && i > 0) { output += ':'; } } alert(output.substring(0, output.length - 1)); 

JSFiddle Work

+2
source
 mystring = mytring.replace(/(.{2})/g, '\:$1').slice(1) 

try it

+1
source

Simple, just map each group of two characters and join the array with ':'

 mystring.match(/.{1,2}/g).join(':') 

 var mystring = '12345678'; document.write(mystring.match(/.{1,2}/g).join(':')) 

no need to cut / trim lines.

+1
source

It’s easier if you customize what you are looking to avoid a colon at the end of the line (using the negative regex look)

 mystring = mystring.replace(/(.{2})(?!$)/g, '\$1:'); 
+1
source

A slightly different approach without regex can use Array.prototype.reduce :

 Array.prototype.reduce.call('12345678', function(acc, item, index){ return acc += index && index % 2 === 0 ? ':' + item : item; }, ''); //12:34:56:78 
+1
source
 mystring = mystring.replace(/(.{2})/g, '$1\:') 

Try

0
source

I like my best approach :)

 function colonizer(strIn){ var rebuiltString = ''; strIn.split('').forEach(function(ltr, i){ (i % 2) ? rebuiltString += ltr + ':' : rebuiltString += ltr; }); return rebuiltString; } alert(colonizer('Nicholas Abrams')); 

Here is a demo

http://codepen.io/anon/pen/BjjNJj

0
source

Source: https://habr.com/ru/post/1238214/


All Articles