Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
Add a colon after two characters without using String.replace

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

about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

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

about 4 years ago · Santiago Gelvez Report

0

Keep it simple. Use string functions to manipulate strings:

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

about 4 years ago · Santiago Gelvez Report

0

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
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!