我正在尝试将一些JavaScript代码从MicrosoftAjax迁移到JQuery。 我使用MicrosoftAjax中流行的.net方法的JavaScript等效方法,例如String.format(),String.startsWith()等。 在jQuery中是否有与它们相当的方法?
我正在尝试将一些JavaScript代码从MicrosoftAjax迁移到JQuery。 我使用MicrosoftAjax中流行的.net方法的JavaScript等效方法,例如String.format(),String.startsWith()等。 在jQuery中是否有与它们相当的方法?
ASP.NET AJAX源代码可供参考,您可以查看它并将您想要继续使用的部分包含在一个单独的JS文件中。或者,您可以将它们移植到jQuery中。
这是format函数的格式...
String.format = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}
这里是endsWith和startsWith原型函数...
String.prototype.endsWith = function (suffix) {
return (this.substr(this.length - suffix.length) === suffix);
}
String.prototype.startsWith = function(prefix) {
return (this.substr(0, prefix.length) === prefix);
}
这是比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
,但也可以使用更冗长的format
。例如:'Hello {0}!'.format(name)
以上许多函数(除了 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 Mitchelmore 提供的另一种很好的实现,包含许多不错的额外特性: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];
});
};
String.prototype
扩展字符串? - Kiquenet有一个(有点)官方的选项: jQuery.validator.format。
至少在 jQuery Validation Plugin 1.6 中提供。
类似于 .NET 中的 String.Format
。
编辑:修复了链接错误。
jQuery.validator.format("{0} {1}", "cool", "formatting") = 'cool formatting'
更多信息请参考http://docs.jquery.com/Plugins/Validation/jQuery.validator.format#templateargumentargumentN...虽然不完全是问题所要求的,但我构建了一个类似的函数,它使用命名占位符而不是按顺序编号。我个人更喜欢使用命名参数,并将对象作为参数传递给它(更冗长,但更易于维护)。
String.prototype.format = function (args) {
var newStr = this;
for (var key in args) {
newStr = newStr.replace('{' + key + '}', args[key]);
}
return newStr;
}
以下是一个使用示例...
alert("Hello {name}".format({ name: 'World' }));
使用支持EcmaScript 2015(ES6)的现代浏览器,您可以享受模板字符串。与格式化不同,您可以直接将变量值注入其中:
var name = "Waleed";
var message = `Hello ${name}!`;
到目前为止,所提供的答案中没有明显的优化方法可以使用封闭来初始化一次并存储正则表达式,以便后续使用。
// 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}"));
虽然已经过了季节,但我刚刚看到了给出的答案,我也想发表一下我的意见:
用法:
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