Home > Net >  Add a colon after two characters without using String.replace
Add a colon after two characters without using String.replace

Time:12-13

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:

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:

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:

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:

You can use template literals:

const x = "1000"
const result = `${x.slice(0, 2)}:${x.slice(2)}`
console.log(result)

CodePudding user response:

You can try a substring, somthing like this

var mystring = '1000';

var method1 = mystring.substring(0, 2)   ':'   mystring.substr(2);

console.log(method1);

and u can make your own function

String.prototype.insert = function(index, string) {
  if (index > 0){
    return this.substring(0, index)   string   this.substr(index);
   }
  return string   this;
};

var mystring='1000';

var method2=mystring.insert(2,':');

console.log(method2);

  • Related