Home > Software engineering >  Add a colon after two characters without using JS replace()
Add a colon after two characters without using JS replace()

Time:12-11

I am currently using replace to insert a colon after the second character of a four-character string (1000). I think it is an elegant solution. But I wonder if there are any other elegant solutions for this? Thanks for your ideas!

Working code

const myStr = "1000";
const string = myStr.replace(/(\d{2})(\d{2})/g, '$1:$2');
console.log(string);

CodePudding user response:

Keep it simple. Use string functions to manipulate strings:

const s1 = "1000";
const s2 = s1.slice(0, 2)   ":"   s1.slice(2);
console.log(s2);

CodePudding user response:

You could stil take a regular expression which works for any time length, like four or six digits with colon for each group of two.

const 
    format = s => s.replace(/.(?=(..) $)/g, '$&:');
    
console.log(format('1000'));
console.log(format('100000'));

CodePudding user response:

Definitely not the best way to do that, i'm just wondering how many alternatives there are

[...'1000'].map((c, i) => i !== 0 && i % 2 === 0 ? `:${c}` : c).join('') //10:00
[...'100000'].map((c, i) => i !== 0 && i % 2 === 0 ? `:${c}` : c).join('') //10:00:00
[...'10000000'].map((c, i) => i !== 0 && i % 2 === 0 ? `:${c}` : c).join('') //10:00:00:00

CodePudding user response:

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
  • Related