在使用
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.