您的位置:首页 > Web前端 > JavaScript

js 自定义format格式化输出

2018-03-09 15:18 274 查看
在使用js的时候,经常要进行字符串的拼接,一但使用+号进行字符串拼接的时候,基本是各种问题,又不好维护,有没有更好的方法地其进行格式化输出呢?答案肯定是有的,如果你使用nodejs,它已经自带的,如果你还在使用纯原生js,那不好意思了。

使用方法

String
对象添加
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'}))
1
输出结果
my name is lake.
1
版权声明:多一份转载,多一份环保 http://blog.csdn.net/dounine/article/details/78443487
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: