爱玩科技网
您的当前位置:首页js中自定义format格式化输出实例

js中自定义format格式化输出实例

来源:爱玩科技网


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

    权声明:多一份转载,多一份环保 http://blog.csdn.net/dounine/article/details/78443487

    在使用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'}))

    输出结果

    my name is lake.
    显示全文