js - 漂亮的format格式化

在使用js的時(shí)候,經(jīng)常要進(jìn)行字符串的拼接,一但使用+號(hào)進(jìn)行字符串拼接的時(shí)候,基本是各種問(wèn)題又不好維護(hù),有沒(méi)有更好的方法地其進(jìn)行格式化輸出呢?答案肯定是有的,如果你使用nodejs,它已經(jīng)自帶的,如果你還在使用純?cè)鷍s,那不好意思了。

使用指南

String對(duì)象添加format方法

String.prototype.format = function(opts) {//use 'my name is ${name}'.format({name:'lake'})
    var data = Array.prototype.slice.call(arguments, 0),
        toString = Object.prototype.toString;
    if (data.length) {
        data = data.length == 1 ?
            (opts !== null && (/\[object Array\]|\[object Object\]/.test(toString.call(opts))) ? opts : data) : data;
        return this.replace(/\$\{(.+?)\}/g, function(match, key) {
            var replacer = data[key];
            // chrome 下 typeof /a/ == 'function'

            if ('[object Function]' == toString.call(replacer)) {
                replacer = replacer(key);
            }
            return ('undefined' == typeof replacer ? '' : replacer);
        });
    }
    return this;
}

使用方法

console.log('my name is ${name}.'.format({name:'lake'}))

輸出結(jié)果

my name is lake.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容