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

147
Views
in Javascript, what is the best practice to convert stringified date to 'YYYY.MM.DD' format?

For example, I get string '20201101'

What I do is convert the string to '2020.11.01'

Here is what I did.

const dateString = '20201101'

const dateArr = dateString.split('')

dateArr.splice(4, 0, '.')
dateArr.splice(7, 0, '.')

const dateFormat = dateArr.join('')

I think it is bit long, so I'm looking for another answer for this.

Thank you!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can also use a RegExp with replacement patterns in a String#replace() call.

const dateStr = '20201101';

const result = dateStr.replace(/(\d{4})(\d{2})(\d{2})/, '$1.$2.$3');

console.log(result)

about 4 years ago · Juan Pablo Isaza Report

0

You could use template literals.

`${dateString.slice(0, 4)}.${dateString.slice(4, 6)}.${dateString.slice(6, 8)}`

Not a very clean way to do it, but it is only one line.

about 4 years ago · Juan Pablo Isaza Report

0

Your code is fine, and readable. But if you're looking for an alternative maybe look at regular expressions.

const str = '20201101';

// Group four digits, then two digits,
// and then two digits
const re = /(\d{4})(\d{2})(\d{2})/;

// `match` returns an array of groups, the first element of
// which will be the initial string, so first remove that,
// and then `join` up the remaining elements using
// a `.` delimiter
const out = str.match(re).slice(1).join('.');

console.log(out);

Additional documentation

  • match
about 4 years ago · Juan Pablo Isaza 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!