js 自定义format格式化输出
2018-03-09 15:18
274 查看
在使用js的时候,经常要进行字符串的拼接,一但使用+号进行字符串拼接的时候,基本是各种问题,又不好维护,有没有更好的方法地其进行格式化输出呢?答案肯定是有的,如果你使用nodejs,它已经自带的,如果你还在使用纯原生js,那不好意思了。
输出结果
版权声明:多一份转载,多一份环保 http://blog.csdn.net/dounine/article/details/78443487
使用方法
为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
相关文章推荐
- js 自定义format格式化输出
- Html Table用JS导出excel格式问题 导出EXCEL后单元格里的000412341234会变成412341234 7-14 会变成 2018-7-14(7月14) 自定义格式 web利用table表格生成excel格式问题 js导出excel增加表头、mso-number-format定义数据格式 数字输出格式转换 mso-number-format:"\@"
- [JS] 如何自定义字符串格式化输出
- javascript Date format(js日期格式化)
- python输出格式化及函数format
- javascript Date format(js日期格式化)
- javascript Date format(js日期格式化)
- C#:String.Format数字格式化输出 {0:N2} {0:D2} {0:C2}...
- javascript Date format(js日期格式化)
- string.Format 格式化输出
- Hadoop案例(五)过滤日志及自定义日志输出路径(自定义OutputFormat)
- c# string.Format 格式化输出
- JS 自定义时间格式化
- 在自己写的formatName基础上,写个,将时间转化为自定义的输出字符串格式信息
- C#:String.Format数字格式化输出
- javascript Date format(js日期格式化)
- python的print格式化输出,以及使用format来控制。
- javascript Date format(js日期格式化)
- javascript Date format(js日期格式化)
- python格式化输出 format