我试图移动一些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
其他回答
上面的许多函数(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
创建了一个以集合或数组作为参数的格式函数
用法:
format("i can speak {language} since i was {age}",{language:'javascript',age:10});
format("i can speak {0} since i was {1}",'javascript',10});
代码:
var format = function (str, col) {
col = typeof col === 'object' ? col : Array.prototype.slice.call(arguments, 1);
return str.replace(/\{\{|\}\}|\{(\w+)\}/g, function (m, n) {
if (m == "{{") { return "{"; }
if (m == "}}") { return "}"; }
return col[n];
});
};
// 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];
});
}
虽然不是防弹衣,但如果你使用得当,还是有用的。
这是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(名字)