例如,我得到字串'20201101'
我所做的是將字串轉換為'2020.11.01'
這就是我所做的。
const dateString = '20201101'
const dateArr = dateString.split('')
dateArr.splice(4, 0, '.')
dateArr.splice(7, 0, '.')
const dateFormat = dateArr.join('')
我認為它有點長,所以我正在尋找另一個答案。
謝謝!
uj5u.com熱心網友回復:
您可以使用模板文字。
`${dateString.slice(0, 4)}.${dateString.slice(4, 6)}.${dateString.slice(6, 8)}`
這不是一種非常干凈的方法,但它只有一條線。
uj5u.com熱心網友回復:
您還可以在呼叫中使用帶有替換模式的RegExp。String#replace()
const dateStr = '20201101';
const result = dateStr.replace(/(\d{4})(\d{2})(\d{2})/, '$1.$2.$3');
console.log(result)
uj5u.com熱心網友回復:
您的代碼很好,并且可讀。但是,如果您正在尋找替代方案,可以查看正則運算式。
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);
附加檔案
match
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/482414.html
標籤:javascript 时间 格式
