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


当前回答

虽然赛季末已经过去了,但我一直在看给出的答案,并得到了我的两便士:

用法:

var one = strFormat('"{0}" is not {1}', 'aalert', 'defined');
var two = strFormat('{0} {0} {1} {2}', 3.14, 'a{2}bc', 'foo');

方法:

function strFormat() {
    var args = Array.prototype.slice.call(arguments, 1);
    return arguments[0].replace(/\{(\d+)\}/g, function (match, index) {
        return args[index];
    });
}

结果:

"aalert" is not defined
3.14 3.14 a{2}bc foo

其他回答

// Regex cache
_stringFormatRegex = null;
//
/// Formats values from {0} to {9}. Usage: stringFormat( 'Hello {0}', 'World' );
stringFormat = function () {
    if (!_stringFormatRegex) {
        // Initialize
        _stringFormatRegex = [];
        for (var i = 0; i < 10; i++) {
            _stringFormatRegex[i] = new RegExp("\\{" + i + "\\}", "gm");
        }
    }
    if (arguments) {
        var s = arguments[0];
        if (s) {
            var L = arguments.length;
            if (1 < L) {
                var r = _stringFormatRegex;
                for (var i = 0; i < L - 1; i++) {
                    var reg = r[i];
                    s = s.replace(reg, arguments[i + 1]);
                }
            }
        }
        return s;
    }
}

这是我的:

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

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

使用支持EcmaScript 2015 (ES6)的现代浏览器,您可以享受模板字符串。而不是格式化,你可以直接注入变量值:

var name = "Waleed";
var message = `Hello ${name}!`;

注意模板字符串必须使用反勾号(')来编写。

我无法让乔希·斯托多拉的答案奏效,但下面的答案对我很管用。注意样机的规格。(在IE, FF, Chrome和Safari上测试):

String.prototype.format = function() {
    var s = this;
    if(t.length - 1 != args.length){
        alert("String.format(): Incorrect number of arguments");
    }
    for (var i = 0; i < arguments.length; i++) {       
        var reg = new RegExp("\\{" + i + "\\}", "gm");
        s = s.replace(reg, arguments[i]);
    }
    return s;
}

S应该是这个的克隆,这样就不会是破坏性的方法,但其实没必要。

这是Josh发布的函数的一个更快/更简单(和原型)的变体:

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

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

用法:

'Added {0} by {1} to your collection'.f(title, artist)
'Your balance is {0} USD'.f(77.7) 

我经常使用它,所以我把它的别名改成了f,但是你也可以使用更详细的格式。如。“你好,{0}!”.format(名字)