我试图移动一些JavaScript代码从MicrosoftAjax到JQuery。我在MicrosoftAjax中使用流行的。net方法的JavaScript等等物,例如String.format(), String.startsWith()等。jQuery中是否有与之对应的函数?
当前回答
这是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(名字)
其他回答
我无法让乔希·斯托多拉的答案奏效,但下面的答案对我很管用。注意样机的规格。(在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应该是这个的克隆,这样就不会是破坏性的方法,但其实没必要。
有一个(有点)官方选项:jQuery.validator.format。
附带jQuery验证插件1.6(至少)。 非常类似于字符串。在. net中找到的格式。
编辑固定破碎的链接。
虽然赛季末已经过去了,但我一直在看给出的答案,并得到了我的两便士:
用法:
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
如果你正在使用验证插件,你可以使用:
jQuery.validator。Format ("{0} {1}", "cool", "formatting") = 'cool formatting'
http://docs.jquery.com/Plugins/Validation/jQuery.validator.format templateargumentargumentN……
在上面adamJLev的精彩回答的基础上,下面是TypeScript版本:
// Extending String prototype
interface String {
format(...params: any[]): string;
}
// Variable number of params, mimicking C# params keyword
// params type is set to any so consumer can pass number
// or string, might be a better way to constraint types to
// string and number only using generic?
String.prototype.format = function (...params: any[]) {
var s = this,
i = params.length;
while (i--) {
s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), params[i]);
}
return s;
};