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

Viewed 54

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!

3 Answers

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.

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

Related