JavaScript 小工具

1. 字符串格式化输出

支持形如:

Orders of {1} or more {0}'

{0},{1}代表第几个参数,包含了完善的异常处理。当给定参数少于格式化串中占位符个数时,未找到的直接留白。

// 格式化字符串
// 包含了异常处理
// formatStr('Orders of {1} or more {0}', 'aaa')
// output: Orders of {1} or more aaa
function formatStr(template, ...args) {
  if (typeof template !== 'string') {
    return template
  }
  if (args.length === 0) {
    return template
  }

  // 通过正则替换%s
  return template.replace(/(\{\d+\})/g, function(match, offset, string) {
    var indexStr = match.slice(1, -1)
    if (indexStr) {
      var index = parseInt(indexStr)
      if (index < args.length) {
        return args[parseInt(index)]
      }
    }
    return match
  })
}
FormatStr

 

posted on 2018-08-11 17:30  一片-枫叶  阅读(409)  评论(0编辑  收藏  举报