简体   繁体   中英

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?

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)

Without the need to remove any trailing colons:

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

\\B matches a zero-width non-word boundary; in other words, when it hits the end of the string, it won't match (as that is considered to be a word boundary) and therefore won't perform the replacement (hence no trailing colon, either).

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

If you're looking for approach other than RegEx, try this:

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));

Working JSFiddle

A somewhat different approach without regex could be using Array.prototype.reduce :

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

试试这个

Easy, just match every group of up-to 2 characters and join the array with ':'

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

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

no string slicing / trimming required.

如果你调整你正在搜索的内容以避免行尾冒号(使用负前瞻正则表达式)会更容易

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

试一试

I like my approach the best :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM