Home > Software design >  in Javascript, what is the best practice to convert stringified date to 'YYYY.MM.DD' forma
in Javascript, what is the best practice to convert stringified date to 'YYYY.MM.DD' forma

Time:05-30

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!

CodePudding user response:

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)

CodePudding user response:

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.

CodePudding user response:

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