Equivalent of String.format in jQuery
我正在尝试将一些JavaScript代码从MicrosoftAjax移到JQuery。 我在流行的.net方法的MicrosoftAjax中使用JavaScript等效项,例如 String.format(),String.startsWith()等。在jQuery中它们是否等效?
ASP.NET AJAX的源代码可供您参考,因此您可以仔细阅读它,并将要继续使用的部分包含在单独的JS文件中。或者,您可以将它们移植到jQuery。
这是格式化功能...
1 2 3 4 5 6 7 8 9 | 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原型函数...
1 2 3 4 5 6 7 | 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发布的功能的更快/更简单(并且是典型的)变体:
1 2 3 4 5 6 7 8 9 | 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; }; |
用法:
1 2 | 'Added {0} by {1} to your collection'.f(title, artist) 'Your balance is {0} USD'.f(77.7) |
我使用了太多的东西,以至于我只将它别名为
上述许多功能(Julian Jelfs除外)均包含以下错误:
1 2 | js> '{0} {0} {1} {2}'.format(3.14, 'a{2}bc', 'foo'); 3.14 3.14 afoobc foo |
或者,对于从参数列表的末尾开始倒数的变体:
1 2 | js> '{0} {0} {1} {2}'.format(3.14, 'a{0}bc', 'foo'); 3.14 3.14 a3.14bc foo |
这是正确的功能。这是朱利安·杰尔夫斯(Julian Jelfs)代码的原型变体,我对此做了更详细的介绍:
1 2 3 4 | String.prototype.format = function () { var args = arguments; return this.replace(/\{(\d+)\}/g, function (m, n) { return args[n]; }); }; |
这是相同版本的稍微高级的版本,它使您可以通过将括号加倍来逃避括号:
1 2 3 4 5 6 7 8 | String.prototype.format = function () { var args = arguments; return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (m, n) { if (m =="{{") { return"{"; } if (m =="}}") { return"}"; } return args[n]; }); }; |
这可以正常工作:
1 2 | 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
制作了以集合或数组为参数的格式函数
用法:
1 2 3 | format("i can speak {language} since i was {age}",{language:'javascript',age:10}); format("i can speak {0} since i was {1}",'javascript',10}); |
码:
1 2 3 4 5 6 7 8 9 | 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]; }); }; |
有(某种)官方选项:jQuery.validator.format。
附带jQuery Validation Plugin 1.6(至少)。
与.NET中的
编辑固定断开的链接。
如果您使用的是验证插件,则可以使用:
http://docs.jquery.com/Plugins/Validation/jQuery.validator.format#templateargumentargumentN ...
尽管不完全是Q的要求,但我建立了一个与Q相似的名称,但使用命名的占位符而不是编号。我个人更喜欢使用命名实参,而只是将对象作为实参发送(更冗长,但更易于维护)。
1 2 3 4 5 6 7 | String.prototype.format = function (args) { var newStr = this; for (var key in args) { newStr = newStr.replace('{' + key + '}', args[key]); } return newStr; } |
这是一个示例用法...
1 | alert("Hello {name}".format({ name: 'World' })); |
使用支持EcmaScript 2015(ES6)的现代浏览器,您可以享受模板字符串。 无需格式化,您可以直接将变量值注入其中:
1 2 | var name ="Waleed"; var message = `Hello ${name}!`; |
请注意,模板字符串必须使用反引号(`)编写。
到目前为止,给出的答案都没有明显的优化,即使用外壳初始化一次并存储正则表达式以供后续使用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | // 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()实现。
这是我的:
1 2 3 4 5 6 7 | String.format = function(tokenised){ var args = arguments; return tokenised.replace(/{[0-9]}/g, function(matched){ matched = matched.replace(/[{}]/g,""); return args[parseInt(matched)+1]; }); } |
不是防弹的,但是如果您明智地使用它,则可以使用。
赛季末已经过去了,但是我一直在寻找给出的答案,并拥有值得我的惊喜:
用法:
1 2 | var one = strFormat('"{0}" is not {1}', 'aalert', 'defined'); var two = strFormat('{0} {0} {1} {2}', 3.14, 'a{2}bc', 'foo'); |
方法:
1 2 3 4 5 6 | function strFormat() { var args = Array.prototype.slice.call(arguments, 1); return arguments[0].replace(/\{(\d+)\}/g, function (match, index) { return args[index]; }); } |
结果:
1 2 | "aalert" is not defined 3.14 3.14 a{2}bc foo |
现在,您可以使用模板文字:
1 2 3 4 5 6 7 8 9 10 11 12 13 | var w ="the Word"; var num1 = 2; var num2 = 3; var long_multiline_string = `This is very long multiline templete string. Putting somthing here: ${w} I can even use expresion interpolation: Two add three = ${num1 + num2} or use Tagged template literals You need to enclose string with the back-tick (\` \`)`; console.log(long_multiline_string); |
以下答案可能是最有效的,但需要注意的是仅适用于参数的1:1映射。这使用了最快的字符串连接方式(类似于stringbuilder:字符串数组,已连接)。这是我自己的代码。虽然可能需要更好的分隔符。
1 2 3 4 5 6 7 8 9 10 | 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(""); } |
像这样使用它:
1 | alert(String.format("~", ["one","two"])); |
这是我的版本,能够转义'{',并清理那些未分配的占位符。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | function getStringFormatPlaceHolderRegEx(placeHolderIndex) { return new RegExp('({)?\\{' + placeHolderIndex + '\\}(?!})', 'gm') } function cleanStringFormatResult(txt) { if (txt == null) return""; return txt.replace(getStringFormatPlaceHolderRegEx("\\d+"),""); } String.prototype.format = function () { var txt = this.toString(); for (var i = 0; i < arguments.length; i++) { var exp = getStringFormatPlaceHolderRegEx(i); txt = txt.replace(exp, (arguments[i] == null ?"" : arguments[i])); } return cleanStringFormatResult(txt); } String.format = function () { var s = arguments[0]; if (s == null) return""; for (var i = 0; i < arguments.length - 1; i++) { var reg = getStringFormatPlaceHolderRegEx(i); s = s.replace(reg, (arguments[i + 1] == null ?"" : arguments[i + 1])); } return cleanStringFormatResult(s); } |
这违反了DRY原则,但这是一个简洁的解决方案:
1 2 | var button = '{text}'; button = button.replace('{text}','Authorize on GitHub').replace('{link}', authorizeUrl); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <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]; } </body> </html> |
扩展上面的adamJLev很好的答案,这是TypeScript版本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // Extending String prototype interface String { format(...params: any[]): string; } // Variable number of params, mimicking C# params keyword // params type is set to any so consumer can pass number // or string, might be a better way to constraint types to // string and number only using generic? String.prototype.format = function (...params: any[]) { var s = this, i = params.length; while (i--) { s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), params[i]); } return s; }; |
我有一个将其添加到字符串原型的插件:
字符串格式
它不仅与其他一些示例一样简短,而且更加灵活。
用法类似于c#版本:
1 2 3 4 | var str2 ="Meet you on {0}, ask for {1}"; var result2 = str2.format("Friday","Suzy"); //result: Meet you on Friday, ask for Suzy //NB: also accepts an array |
此外,还增加了对使用名称和对象属性的支持
1 2 3 | var str1 ="Meet you on {day}, ask for {Person}"; var result1 = str1.format({day:"Thursday", person:"Frank"}); //result: Meet you on Thursday, ask for Frank |
您也可以像这样用替换来关闭数组。
1 2 | var url = '/getElement/_/_/_'.replace(/_/g, (_ => this.ar[this.i++]).bind({ar: ["invoice","id", 1337],i: 0})) > '/getElement/invoice/id/1337 |
或者您可以尝试
1 | '/getElement/_/_/_'.replace(/_/g, (function(_) {return this.ar[this.i++];}).bind({ar: ["invoice","id", 1337],i: 0})) |
我无法获得Josh Stodola的工作答案,但以下内容对我有用。注意
1 2 3 4 5 6 7 8 9 10 11 | 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; } |