Wal*_*ssa 190 javascript jquery string.format
我正在尝试将一些JavaScript代码从MicrosoftAjax移动到JQuery.我使用流行的.net方法的MicrosoftAjax中的JavaScript等价物,例如String.format(),String.startsWith()等.在jQuery中它们是否等同于它们?
Jos*_*ola 192
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;
}
Run Code Online (Sandbox Code Playgroud)
这里有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);
}
Run Code Online (Sandbox Code Playgroud)
ada*_*Lev 146
这是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;
};
Run Code Online (Sandbox Code Playgroud)
用法:
'Added {0} by {1} to your collection'.f(title, artist)
'Your balance is {0} USD'.f(77.7)
Run Code Online (Sandbox Code Playgroud)
我使用它太多了,我把它别名f,但你也可以使用更详细的format.例如'Hello {0}!'.format(name)
gpv*_*vos 131
许多上述函数(Julian Jelfs除外)包含以下错误:
js> '{0} {0} {1} {2}'.format(3.14, 'a{2}bc', 'foo');
3.14 3.14 afoobc foo
Run Code Online (Sandbox Code Playgroud)
或者,对于从参数列表末尾向后计数的变体:
js> '{0} {0} {1} {2}'.format(3.14, 'a{0}bc', 'foo');
3.14 3.14 a3.14bc foo
Run Code Online (Sandbox Code Playgroud)
这是一个正确的功能.它是Julian Jelfs代码的原型变体,我做了一些更紧凑的代码:
String.prototype.format = function () {
var args = arguments;
return this.replace(/\{(\d+)\}/g, function (m, n) { return args[n]; });
};
Run Code Online (Sandbox Code Playgroud)
这里有一个稍高级的版本,允许你通过加倍来逃避括号:
String.prototype.format = function () {
var args = arguments;
return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (m, n) {
if (m == "{{") { return "{"; }
if (m == "}}") { return "}"; }
return args[n];
});
};
Run Code Online (Sandbox Code Playgroud)
这工作正常:
js> '{0} {{0}} {{{0}}} {1} {2}'.format(3.14, 'a{2}bc', 'foo');
3.14 {0} {3.14} a{2}bc foo
Run Code Online (Sandbox Code Playgroud)
这是Blair Mitchelmore的另一个很好的实现,带有一些很好的额外功能:https://web.archive.org/web/20120315214858/http://blairmitchelmore.com/javascript/string.format
ian*_*anj 48
制作了一个格式函数,它将集合或数组作为参数
用法:
format("i can speak {language} since i was {age}",{language:'javascript',age:10});
format("i can speak {0} since i was {1}",'javascript',10});
Run Code Online (Sandbox Code Playgroud)
码:
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];
});
};
Run Code Online (Sandbox Code Playgroud)
rse*_*nna 36
有一个(某种程度上)官方选项:jQuery.validator.format.
附带jQuery Validation Plugin 1.6(至少).
与String.Format.NET中的相似.
编辑修复损坏的链接.
fie*_*sey 17
如果您使用的是验证插件,则可以使用:
jQuery.validator.format("{0} {1}", "cool", "formatting") = 'cool formatting'
http://docs.jquery.com/Plugins/Validation/jQuery.validator.format#templateargumentargumentN ...
Bri*_*ian 13
虽然不完全是Q所要求的,但我已经构建了一个类似但使用命名占位符而不是编号的.我个人更喜欢命名参数,只是发送一个对象作为参数(更详细,但更容易维护).
String.prototype.format = function (args) {
var newStr = this;
for (var key in args) {
newStr = newStr.replace('{' + key + '}', args[key]);
}
return newStr;
}
Run Code Online (Sandbox Code Playgroud)
这是一个示例用法......
alert("Hello {name}".format({ name: 'World' }));
Run Code Online (Sandbox Code Playgroud)
小智 6
到目前为止,所提出的答案都没有明显优化使用机箱初始化一次并存储正则表达式,以便后续使用.
// 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}"));
Run Code Online (Sandbox Code Playgroud)
此外,如果已经存在,则没有一个示例尊重format()实现.
使用支持EcmaScript 2015(ES6)的现代浏览器,您可以享受模板字符串.您可以直接将变量值注入其中,而不是格式化:
var name = "Waleed";
var message = `Hello ${name}!`;
Run Code Online (Sandbox Code Playgroud)
注意,模板字符串必须使用反向标记(`)来编写.
赛季后期已经过去了,但我一直在看给出的答案,并让我的 tuppence 值:
用法:
var one = strFormat('"{0}" is not {1}', 'aalert', 'defined');
var two = strFormat('{0} {0} {1} {2}', 3.14, 'a{2}bc', 'foo');
Run Code Online (Sandbox Code Playgroud)
方法:
function strFormat() {
var args = Array.prototype.slice.call(arguments, 1);
return arguments[0].replace(/\{(\d+)\}/g, function (match, index) {
return args[index];
});
}
Run Code Online (Sandbox Code Playgroud)
结果:
"aalert" is not defined
3.14 3.14 a{2}bc foo
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
255806 次 |
| 最近记录: |