我试图移动一些JavaScript代码从MicrosoftAjax到JQuery。我在MicrosoftAjax中使用流行的。net方法的JavaScript等等物,例如String.format(), String.startsWith()等。jQuery中是否有与之对应的函数?
当前回答
创建了一个以集合或数组作为参数的格式函数
用法:
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;
}
}
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);
}
虽然赛季末已经过去了,但我一直在看给出的答案,并得到了我的两便士:
用法:
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
使用支持EcmaScript 2015 (ES6)的现代浏览器,您可以享受模板字符串。而不是格式化,你可以直接注入变量值:
var name = "Waleed";
var message = `Hello ${name}!`;
注意模板字符串必须使用反勾号(')来编写。
有一个(有点)官方选项:jQuery.validator.format。
附带jQuery验证插件1.6(至少)。 非常类似于字符串。在. net中找到的格式。
编辑固定破碎的链接。