良好的代碼閱讀體驗(yàn) && 最新版本济丘,移步 作業(yè)部落 (3) 字符串處理
基礎(chǔ)編程中,幾乎無時不刻都需要對字符串的進(jìn)行處理弯院。
推薦一個輪子泪掀,underscore 是一個強(qiáng)大的字符串處理庫。
字符串格式化
ES6代碼規(guī)范中异赫,實(shí)現(xiàn)有 Template strings 屬性。
在node util 模塊內(nèi)有 util.format 方法塔拳,可以實(shí)現(xiàn)字符串格式化。
不完美的 ES3 實(shí)現(xiàn)
String.prototype.template.js量九,從性能和可維護(hù)來說颂碧,不是很實(shí)用,看下js的各種神奇寫法還行载城。
node util.format 源碼簡化版
browse && node support,移除了 inspect 特性
'use strict'
/**
* 使用示例
* format('i am %s,top %d %%,more detail %j','lilei','23',{'height':'176cm'})
* i am lilei,top 23 %,more detail {"height":"176cm"}
* @return {str}
*
* edit by plusmancn@gmail.com wechat@plusman
*/
function format(f) {
var formatRegExp = /%[sdj%]/g;
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
return str;
};
簡易format實(shí)現(xiàn)
'use strict'
/**
* JS字符串格式化函數(shù)
*
* 使用示例
* "you say {0} to who,so {1} say {0} to you too".format('world','Julia');
* //output you say world to me,so Julia say world to you too
*
* edit by plusmancn@gmail.com wechat@plusman
*/
String.prototype.format = function() {
var args = Array.prototype.slice.call(arguments);
return this.replace(/\{(\d+)\}/g,function(all,k){
return args[k];
});
};
C風(fēng)格sprintf函數(shù)
移步 sprintf.js