良好的代码阅读体验 && 最新版本,移步 作业部落 (3) 字符串处理
基础编程中,几乎无时不刻都需要对字符串的进行处理。
推荐一个轮子,underscore 是一个强大的字符串处理库。
字符串格式化
ES6代码规范中,实现有 Template strings 属性。
在node util 模块内有 util.format 方法,可以实现字符串格式化。
不完美的 ES3 实现
String.prototype.template.js,从性能和可维护来说,不是很实用,看下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实现
'use strict'
/**
* JS字符串格式化函数
*
* 使用示例
* "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风格sprintf函数
移步 sprintf.js