JavaScript:如何使用 format 格式化字符串


#Web 前端开发#


在 Java 等编程语言中有 String.format 方法用来组装字符串,非常方便。

而 JavaScript 中好像只能是通过加号组装:

var s = "Hello " + " World"

有类似 String.format 的函数吗?有,但要自己实现。

方式1:使用ES6

在最新的 Chrome 等浏览器中已经支持 ES6 了。

var name = 'letian'
var s = `Hello ${name}`
console.log(s)

方法2:在 String 原型中增加 format 函数

String.prototype.format = function() {
    var formatted = this;
    for( var arg in arguments ) {
        formatted = formatted.replace("{" + arg + "}", arguments[arg]);
    }
    return formatted;
};

var s = '你好 {0} {1}'.formar('value1', 123)
console.log(s)

运行结果:

你好 value1 123

但是**上面这个实现有 bug**,比如 '{0} {1}'.format('{1}', '{0}') 的结果是 {0} {1},这个和预期的 {1} {0} 不一致。

修复如下:

if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}

如果不想在字符串后面加.format,可以用 String.format 方法,那么可以用下面的实现:

if (!String.format) {
  String.format = function(format) {
    var args = Array.prototype.slice.call(arguments, 1);
    return format.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number] 
        : match
      ;
    });
  };
}

使用示例: String.format('{0}', 'Hello')

方法3: sprintf.js 库

https://github.com/alexei/sprintf.js

参考


( 本文完 )