我试图移动一些JavaScript代码从MicrosoftAjax到JQuery。我在MicrosoftAjax中使用流行的。net方法的JavaScript等等物,例如String.format(), String.startsWith()等。jQuery中是否有与之对应的函数?


当前回答

上面的许多函数(Julian Jelfs的除外)包含以下错误:

js> '{0} {0} {1} {2}'.format(3.14, 'a{2}bc', 'foo');
3.14 3.14 afoobc foo

或者,对于从参数列表末尾开始向后计数的变量:

js> '{0} {0} {1} {2}'.format(3.14, 'a{0}bc', 'foo');
3.14 3.14 a3.14bc foo

这是一个正确的函数。这是Julian Jelfs代码的原型变体,我把它做得更紧凑:

String.prototype.format = function () {
  var args = arguments;
  return this.replace(/\{(\d+)\}/g, function (m, n) { return args[n]; });
};

这里有一个稍微高级一点的版本,它允许你通过重复大括号来转义:

String.prototype.format = function () {
  var args = arguments;
  return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (m, n) {
    if (m == "{{") { return "{"; }
    if (m == "}}") { return "}"; }
    return args[n];
  });
};

这是正确的:

js> '{0} {{0}} {{{0}}} {1} {2}'.format(3.14, 'a{2}bc', 'foo');
3.14 {0} {3.14} a{2}bc foo

下面是Blair mitchell的另一个很好的实现,它有很多不错的额外特性:https://web.archive.org/web/20120315214858/http://blairmitchelmore.com/javascript/string.format

其他回答

我有一个活塞,将其添加到字符串原型: string.format 它不仅像其他一些例子一样简短,而且灵活得多。

用法类似于c#版本:

var str2 = "Meet you on {0}, ask for {1}";
var result2 = str2.format("Friday", "Suzy"); 
//result: Meet you on Friday, ask for Suzy
//NB: also accepts an array

另外,增加了对使用名称和对象属性的支持

var str1 = "Meet you on {day}, ask for {Person}";
var result1 = str1.format({day: "Thursday", person: "Frank"}); 
//result: Meet you on Thursday, ask for Frank

上面的许多函数(Julian Jelfs的除外)包含以下错误:

js> '{0} {0} {1} {2}'.format(3.14, 'a{2}bc', 'foo');
3.14 3.14 afoobc foo

或者,对于从参数列表末尾开始向后计数的变量:

js> '{0} {0} {1} {2}'.format(3.14, 'a{0}bc', 'foo');
3.14 3.14 a3.14bc foo

这是一个正确的函数。这是Julian Jelfs代码的原型变体,我把它做得更紧凑:

String.prototype.format = function () {
  var args = arguments;
  return this.replace(/\{(\d+)\}/g, function (m, n) { return args[n]; });
};

这里有一个稍微高级一点的版本,它允许你通过重复大括号来转义:

String.prototype.format = function () {
  var args = arguments;
  return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (m, n) {
    if (m == "{{") { return "{"; }
    if (m == "}}") { return "}"; }
    return args[n];
  });
};

这是正确的:

js> '{0} {{0}} {{{0}}} {1} {2}'.format(3.14, 'a{2}bc', 'foo');
3.14 {0} {3.14} a{2}bc foo

下面是Blair mitchell的另一个很好的实现,它有很多不错的额外特性:https://web.archive.org/web/20120315214858/http://blairmitchelmore.com/javascript/string.format

这是我的:

String.format = function(tokenised){
        var args = arguments;
        return tokenised.replace(/{[0-9]}/g, function(matched){
            matched = matched.replace(/[{}]/g, "");
            return args[parseInt(matched)+1];             
        });
    }

虽然不是防弹衣,但如果你使用得当,还是有用的。

你也可以这样替换闭包数组。

var url = '/getElement/_/_/_'.replace(/_/g, (_ => this.ar[this.i++]).bind({ar: ["invoice", "id", 1337],i: 0}))
> '/getElement/invoice/id/1337

或者您可以尝试bind

'/getElement/_/_/_'.replace(/_/g, (function(_) {return this.ar[this.i++];}).bind({ar: ["invoice", "id", 1337],i: 0}))

到目前为止,所有给出的答案都没有明显的优化,即使用enclosure来初始化一次并存储正则表达式,以供后续使用。

// DBJ.ORG string.format function
// usage:   "{0} means 'zero'".format("nula") 
// returns: "nula means 'zero'"
// place holders must be in a range 0-99.
// if no argument given for the placeholder, 
// no replacement will be done, so
// "oops {99}".format("!")
// returns the input
// same placeholders will be all replaced 
// with the same argument :
// "oops {0}{0}".format("!","?")
// returns "oops !!"
//
if ("function" != typeof "".format) 
// add format() if one does not exist already
  String.prototype.format = (function() {
    var rx1 = /\{(\d|\d\d)\}/g, rx2 = /\d+/ ;
    return function() {
        var args = arguments;
        return this.replace(rx1, function($0) {
            var idx = 1 * $0.match(rx2)[0];
            return args[idx] !== undefined ? args[idx] : (args[idx] === "" ? "" : $0);
        });
    }
}());

alert("{0},{0},{{0}}!".format("{X}"));

此外,如果已经存在format()实现,那么所有示例都不尊重它。