JavaScript字串Format

來源:互聯網
上載者:User

標籤:this   str   welcome   asc   fine   可讀性   blog   分享   一個   

一直用C#編程,在日常字串拼接中string.Format()一直是個很好用很常用的方法,不用自己+++,既影響開發效率也影響可讀性

然而在js中並沒有這樣的函數可供使用,so整理了一個js的字串format函數供項目的日常使用

雖然並不是很完善也不能提升拼接效率,但是足夠滿足開發過程中的工作效率和可讀性

 

通過String類型的原型prototype新增一個format方法,方便使用

String.prototype.format = function () {    if (arguments.length === 0) return this;    var result = this;    if (arguments.length === 1 && typeof arguments[0] === ‘object‘) {        for (var key in arguments[0]) {            if (arguments[0][key] === undefined) continue;            result = result.replace(new RegExp("({" + key + "})", "g"), arguments[0][key]);        }    } else {        for (var i = 0; i < arguments.length; i++) {            if (arguments[i] === undefined) continue;            result = result.replace(new RegExp("({[" + i + "]})", "g"), arguments[i]);        }    }    return result.toString();}

測試一下:

‘Welcome to {city}! My name is {name}.‘.format({ city: ‘阜寧‘, name: ‘戀禾夢穎‘ });‘Total num is {0},total price is ${1}‘.format(2, 10);

測試結果:

 

JavaScript字串Format

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.