您的当前位置:首页正文

(2)字符串处理

来源:要发发知识网



字符串格式化

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   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   wechat@plusman
 */
String.prototype.format = function() {
  var args = Array.prototype.slice.call(arguments);
  return this.replace(/\{(\d+)\}/g,function(all,k){
    return args[k];
  });
};