82

C# 具有非常强大String.Format()的替换元素的功能,例如{0}参数。JavaScript是否有等价物?

4

4 回答 4

88

为 javascript尝试sprintf()

或者

// First, checks if it isn't implemented yet.
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
      ;
    });
  };
}

"{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")

JavaScript 中提取的两个答案都等同于 printf/string.format

于 2013-08-23T14:49:31.097 回答
32

我在用:

String.prototype.format = function() {
    var s = this,
        i = arguments.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return s;
};

用法:"Hello {0}".format("World");

我在Equivalent of String.format in JQuery 中找到了它

更新:

例如,在 ES6/ES2015 中,您可以使用字符串模板

'use strict';

let firstName = 'John',
    lastName = 'Smith';

console.log(`Full Name is ${firstName} ${lastName}`); 
// or
console.log(`Full Name is ${firstName + ' ' + lastName}');
于 2014-02-18T03:54:06.377 回答
17

基于@Vlad Bezden 的回答,我使用了这个稍作修改的代码,因为我更喜欢命名占位符:

String.prototype.format = function(placeholders) {
    var s = this;
    for(var propertyName in placeholders) {
        var re = new RegExp('{' + propertyName + '}', 'gm');
        s = s.replace(re, placeholders[propertyName]);
    }    
    return s;
};

用法:

"{greeting} {who}!".format({greeting: "Hello", who: "world"})

String.prototype.format = function(placeholders) {
    var s = this;
    for(var propertyName in placeholders) {
        var re = new RegExp('{' + propertyName + '}', 'gm');
        s = s.replace(re, placeholders[propertyName]);
    }    
    return s;
};

$("#result").text("{greeting} {who}!".format({greeting: "Hello", who: "world"}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>

于 2014-11-01T11:58:21.217 回答
15

我很久以前创建它,相关问题

String.Format = function (b) {
    var a = arguments;
    return b.replace(/(\{\{\d\}\}|\{\d\})/g, function (b) {
        if (b.substring(0, 2) == "{{") return b;
        var c = parseInt(b.match(/\d/)[0]);
        return a[c + 1]
    })
};
于 2013-08-23T14:54:16.613 回答