javascript中對數據文本格式化的思考

在實際應用場景中,咱們經常需將一些數據輸出成更加符合人類習慣閱讀的格式。函數

保留小數點後面兩位

在一些要求精度沒有那麼準確的場景下,咱們能夠直接經過Number.prototype.toFixed()來實現保留小數點兩位這樣的需求。prototype

var num = 123.45678
console.log(num.toFixed(2)) //123.46

var num2 = 12
console.log(num2.toFixed(2)) //12.00

不過若是剛好,數字是一個整數,那麼就會輸出12.00這樣的格式,咱們經常對於後面爲00的整數要求直接輸出整數便可。所以不妨這樣寫。code

var num = 123.45678
console.log(num.toFixed(2).replace('.00', '')) //123.46

var num2 = 12
console.log(num2.toFixed(2).replace('.00', '')) //12

toFixed()後面直接接着replace()將整數纔會出現的.00字符串替換掉便可。orm

ps: Number.prototype.toFixed返回的是一個字符串對象

數字爲[0-9]的狀況下,前置補0

在輸出某些數字的時候下,若是是小於10的狀況下須要在前面補0,尤爲是在輸出日期時間的時候。字符串

之前在用Date對象去獲取到相關的時間數據的時候去判斷是否小於10,若是是就補0get

var date = new Date()
var min = date.getMinutes()
min = min < 10 ? '0' + min : min
console.log(min) //08

後來以爲實在不夠優雅,並且代碼繁多,就想到用字符串替換的方式。string

var date = new Date()
var min = String(date.getMinutes()).replace(/^(\d{1})$/, '0$1')
console.log(min) //08

這樣利用正則去匹配到單數字的狀況下直接在前面加上0便可,一行代碼,更加優雅。io

再繼續衍生下去,我基本上都是在日期格式化的時候須要作數字替換,何不直接整個字符串替換便可?好比將2017-1-8 12:8替換成2017-01-08 12:08console

var date = '2017-1-8 12:8'.replace(/\b\d{1}\b/g, '0$&')
console.log(date)

經過正則去作整個字符串替換,再也不針對性的針對某些部分作處理了。 最後給出完整的格式化日期函數示例。

function formatDate (source,  format = 'yyyy-MM-dd') {
    let date = new Date();
    if (typeof source === 'string') format = source;
    if (typeof source === 'number') date = new Date(source);
    if (typeof source === 'object') date = source;

    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const miniute = date.getMinutes();
    const second = date.getSeconds();
    return format.replace('yyyy', year)
                  .replace('MM', month)
                  .replace('dd', day)
                  .replace('hh', hour)
                  .replace('mm', miniute)
                  .replace('ss', second)
                  .replace(/\b\d{1}\b/g, '0$&');
}
上面列舉的全部代碼,都沒有考察對比過執行效率,由於在這些應用場景下,效率是其次問題。
相關文章
相關標籤/搜索