我试图移动一些JavaScript代码从MicrosoftAjax到JQuery。我在MicrosoftAjax中使用流行的。net方法的JavaScript等等物,例如String.format(), String.startsWith()等。jQuery中是否有与之对应的函数?
当前回答
我无法让乔希·斯托多拉的答案奏效,但下面的答案对我很管用。注意样机的规格。(在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应该是这个的克隆,这样就不会是破坏性的方法,但其实没必要。
其他回答
// 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;
}
}
下面的答案可能是最有效的,但它只适用于参数的1对1映射。这使用了连接字符串的最快方式(类似于stringbuilder:字符串数组,连接)。这是我自己的代码。可能需要一个更好的分离器。
String.format = function(str, args)
{
var t = str.split('~');
var sb = [t[0]];
for(var i = 0; i < args.length; i++){
sb.push(args[i]);
sb.push(t[i+1]);
}
return sb.join("");
}
像这样使用它:
alert(String.format("<a href='~'>~</a>", ["one", "two"]));
这是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(名字)
这违反了DRY原则,但这是一个简洁的解决方案:
var button = '<a href="{link}" class="btn">{text}</a>';
button = button.replace('{text}','Authorize on GitHub').replace('{link}', authorizeUrl);
到目前为止,所有给出的答案都没有明显的优化,即使用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()实现,那么所有示例都不尊重它。