我试图移动一些JavaScript代码从MicrosoftAjax到JQuery。我在MicrosoftAjax中使用流行的。net方法的JavaScript等等物,例如String.format(), String.startsWith()等。jQuery中是否有与之对应的函数?
当前回答
ASP的源代码。NET AJAX可供您参考,因此您可以从中挑选并将想要继续使用的部分包含到单独的JS文件中。或者,您可以将它们移植到jQuery。
这里是格式函数…
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);
}
其他回答
有一个(有点)官方选项:jQuery.validator.format。
附带jQuery验证插件1.6(至少)。 非常类似于字符串。在. net中找到的格式。
编辑固定破碎的链接。
上面的许多函数(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
使用支持EcmaScript 2015 (ES6)的现代浏览器,您可以享受模板字符串。而不是格式化,你可以直接注入变量值:
var name = "Waleed";
var message = `Hello ${name}!`;
注意模板字符串必须使用反勾号(')来编写。
虽然赛季末已经过去了,但我一直在看给出的答案,并得到了我的两便士:
用法:
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
<html>
<body>
<script type="text/javascript">
var str="http://xyz.html?ID={0}&TId={1}&STId={2}&RId={3},14,480,3,38";
document.write(FormatString(str));
function FormatString(str) {
var args = str.split(',');
for (var i = 0; i < args.length; i++) {
var reg = new RegExp("\\{" + i + "\\}", "");
args[0]=args[0].replace(reg, args [i+1]);
}
return args[0];
}
</script>
</body>
</html>