这让我疯了.我相信我问了同样的问题,但我再也找不到了(我使用Stack Overflow搜索,Google搜索,手动搜索我的帖子,搜索我的代码).
我想要的东西就像C#String.Format,你可以做类似的事情
string format = String.Format("Hi {0}",name);
当然只是为JavaScript而且有一个人给了我一个简单的答案,它不像jQuery插件或任何东西,但我认为你做了一些JSON的东西,它工作起来很简单.
我为我的生活找不到这篇文章.
我在我的代码中确实有这个,但我似乎找不到任何使用它的东西,我很确定我曾经使用过几次:
String.prototype.format = function(o) { return this.replace(/{([^{}]*)}/g, function(a, b) { var r = o[b]; return typeof r === 'string' ? r : a; } ); };
Sky Sanders.. 71
调整MsAjax字符串中的代码.
只需删除所有_validateParams
代码,您就可以在JavaScript中使用完整的.NET字符串类.
好的,我解放了msajax字符串类,删除了所有msajax依赖项.它很棒,就像.NET字符串类一样,包括trim函数,endsWith/startsWith等.
PS - 我保留了所有Visual Studio JavaScript IntelliSense助手和XmlDocs.如果您不使用Visual Studio,它们是无害的,但如果您愿意,可以删除它们.
// String.js - liberated from MicrosoftAjax.js on 03/28/10 by Sky Sanders // permalink: http://stackoverflow.com/a/2534834/2343 /* Copyright (c) 2009, CodePlex Foundation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of CodePlex Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function(window) { $type = String; $type.__typeName = 'String'; $type.__class = true; $prototype = $type.prototype; $prototype.endsWith = function String$endsWith(suffix) { ///Determines whether the end of this instance matches the specified string. /// A string to compare to. ///true if suffix matches the end of this instance; otherwise, false. return (this.substr(this.length - suffix.length) === suffix); } $prototype.startsWith = function String$startsWith(prefix) { ///Determines whether the beginning of this instance matches the specified string. /// The String to compare. ///true if prefix matches the beginning of this string; otherwise, false. return (this.substr(0, prefix.length) === prefix); } $prototype.trim = function String$trim() { ///Removes all leading and trailing white-space characters from the current String object. ///The string that remains after all white-space characters are removed from the start and end of the current String object. return this.replace(/^\s+|\s+$/g, ''); } $prototype.trimEnd = function String$trimEnd() { ///Removes all trailing white spaces from the current String object. ///The string that remains after all white-space characters are removed from the end of the current String object. return this.replace(/\s+$/, ''); } $prototype.trimStart = function String$trimStart() { ///Removes all leading white spaces from the current String object. ///The string that remains after all white-space characters are removed from the start of the current String object. return this.replace(/^\s+/, ''); } $type.format = function String$format(format, args) { ///Replaces the format items in a specified String with the text equivalents of the values of corresponding object instances. The invariant culture will be used to format dates and numbers. /// A format string. /// The objects to format. ///A copy of format in which the format items have been replaced by the string equivalent of the corresponding instances of object arguments. return String._toFormattedString(false, arguments); } $type._toFormattedString = function String$_toFormattedString(useLocale, args) { var result = ''; var format = args[0]; for (var i = 0; ; ) { // Find the next opening or closing brace var open = format.indexOf('{', i); var close = format.indexOf('}', i); if ((open < 0) && (close < 0)) { // Not found: copy the end of the string and break result += format.slice(i); break; } if ((close > 0) && ((close < open) || (open < 0))) { if (format.charAt(close + 1) !== '}') { throw new Error('format stringFormatBraceMismatch'); } result += format.slice(i, close + 1); i = close + 2; continue; } // Copy the string before the brace result += format.slice(i, open); i = open + 1; // Check for double braces (which display as one and are not arguments) if (format.charAt(i) === '{') { result += '{'; i++; continue; } if (close < 0) throw new Error('format stringFormatBraceMismatch'); // Find the closing brace // Get the string between the braces, and split it around the ':' (if any) var brace = format.substring(i, close); var colonIndex = brace.indexOf(':'); var argNumber = parseInt((colonIndex < 0) ? brace : brace.substring(0, colonIndex), 10) + 1; if (isNaN(argNumber)) throw new Error('format stringFormatInvalid'); var argFormat = (colonIndex < 0) ? '' : brace.substring(colonIndex + 1); var arg = args[argNumber]; if (typeof (arg) === "undefined" || arg === null) { arg = ''; } // If it has a toFormattedString method, call it. Otherwise, call toString() if (arg.toFormattedString) { result += arg.toFormattedString(argFormat); } else if (useLocale && arg.localeFormat) { result += arg.localeFormat(argFormat); } else if (arg.format) { result += arg.format(argFormat); } else result += arg.toString(); i = close + 1; } return result; } })(window);
@Sean,我没有编写代码或注释,我只是从msajax中获取字符串类并删除/替换了所有外部依赖项.这为您提供了许多来自.net的非常有用和熟悉的字符串函数.我想如果你要做某事,那就做对了.琐碎,脆弱的字符串改变片段令人头疼. (2认同)
Jeremy.. 42
这是我使用的.我在实用程序文件中定义了此函数:
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; }
我称之为:
var greeting = String.format("Hi, {0}", name);
我不记得我发现了什么,但它对我来说非常有用.我喜欢它,因为语法与C#版本相同.
调整MsAjax字符串中的代码.
只需删除所有_validateParams
代码,您就可以在JavaScript中使用完整的.NET字符串类.
好的,我解放了msajax字符串类,删除了所有msajax依赖项.它很棒,就像.NET字符串类一样,包括trim函数,endsWith/startsWith等.
PS - 我保留了所有Visual Studio JavaScript IntelliSense助手和XmlDocs.如果您不使用Visual Studio,它们是无害的,但如果您愿意,可以删除它们.
// String.js - liberated from MicrosoftAjax.js on 03/28/10 by Sky Sanders // permalink: http://stackoverflow.com/a/2534834/2343 /* Copyright (c) 2009, CodePlex Foundation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of CodePlex Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function(window) { $type = String; $type.__typeName = 'String'; $type.__class = true; $prototype = $type.prototype; $prototype.endsWith = function String$endsWith(suffix) { ///Determines whether the end of this instance matches the specified string. /// A string to compare to. ///true if suffix matches the end of this instance; otherwise, false. return (this.substr(this.length - suffix.length) === suffix); } $prototype.startsWith = function String$startsWith(prefix) { ///Determines whether the beginning of this instance matches the specified string. /// The String to compare. ///true if prefix matches the beginning of this string; otherwise, false. return (this.substr(0, prefix.length) === prefix); } $prototype.trim = function String$trim() { ///Removes all leading and trailing white-space characters from the current String object. ///The string that remains after all white-space characters are removed from the start and end of the current String object. return this.replace(/^\s+|\s+$/g, ''); } $prototype.trimEnd = function String$trimEnd() { ///Removes all trailing white spaces from the current String object. ///The string that remains after all white-space characters are removed from the end of the current String object. return this.replace(/\s+$/, ''); } $prototype.trimStart = function String$trimStart() { ///Removes all leading white spaces from the current String object. ///The string that remains after all white-space characters are removed from the start of the current String object. return this.replace(/^\s+/, ''); } $type.format = function String$format(format, args) { ///Replaces the format items in a specified String with the text equivalents of the values of corresponding object instances. The invariant culture will be used to format dates and numbers. /// A format string. /// The objects to format. ///A copy of format in which the format items have been replaced by the string equivalent of the corresponding instances of object arguments. return String._toFormattedString(false, arguments); } $type._toFormattedString = function String$_toFormattedString(useLocale, args) { var result = ''; var format = args[0]; for (var i = 0; ; ) { // Find the next opening or closing brace var open = format.indexOf('{', i); var close = format.indexOf('}', i); if ((open < 0) && (close < 0)) { // Not found: copy the end of the string and break result += format.slice(i); break; } if ((close > 0) && ((close < open) || (open < 0))) { if (format.charAt(close + 1) !== '}') { throw new Error('format stringFormatBraceMismatch'); } result += format.slice(i, close + 1); i = close + 2; continue; } // Copy the string before the brace result += format.slice(i, open); i = open + 1; // Check for double braces (which display as one and are not arguments) if (format.charAt(i) === '{') { result += '{'; i++; continue; } if (close < 0) throw new Error('format stringFormatBraceMismatch'); // Find the closing brace // Get the string between the braces, and split it around the ':' (if any) var brace = format.substring(i, close); var colonIndex = brace.indexOf(':'); var argNumber = parseInt((colonIndex < 0) ? brace : brace.substring(0, colonIndex), 10) + 1; if (isNaN(argNumber)) throw new Error('format stringFormatInvalid'); var argFormat = (colonIndex < 0) ? '' : brace.substring(colonIndex + 1); var arg = args[argNumber]; if (typeof (arg) === "undefined" || arg === null) { arg = ''; } // If it has a toFormattedString method, call it. Otherwise, call toString() if (arg.toFormattedString) { result += arg.toFormattedString(argFormat); } else if (useLocale && arg.localeFormat) { result += arg.localeFormat(argFormat); } else if (arg.format) { result += arg.format(argFormat); } else result += arg.toString(); i = close + 1; } return result; } })(window);
这是我使用的.我在实用程序文件中定义了此函数:
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; }
我称之为:
var greeting = String.format("Hi, {0}", name);
我不记得我发现了什么,但它对我来说非常有用.我喜欢它,因为语法与C#版本相同.
你可以做一系列替换:
function format(str) { for(i = 1; i < arguments.length; i++) { str = str.replace('{' + (i - 1) + '}', arguments[i]); } return str; }
更好的方法是使用replace函数参数:
function format(str, obj) { return str.replace(/\{\s*([^}\s]+)\s*\}/g, function(m, p1, offset, string) { return obj[p1] }) }
这样您就可以提供索引和命名参数:
var arr = ['0000', '1111', '2222'] arr.a = 'aaaa' str = format(" { 0 } , {1}, { 2}, {a}", arr) // returns 0000 , 1111, 2222, aaaa
没有第三方功能:
string format = "Hi {0}".replace('{0}', name)
有多个参数:
string format = "Hi {0} {1}".replace('{0}', name).replace('{1}', lastname)
这是一个有用的字符串格式化函数,使用正则表达式和捕获:
function format (fmtstr) { var args = Array.prototype.slice.call(arguments, 1); return fmtstr.replace(/\{(\d+)\}/g, function (match, index) { return args[index]; }); }
字符串可以格式化为C#String.Format:
var str = format('{0}, {1}!', 'Hello', 'world'); console.log(str); // prints "Hello, world!"
格式将正确的变量放在正确的位置,即使它们出现乱序:
var str = format('{1}, {0}!', 'Hello', 'world'); console.log(str); // prints "world, Hello!"
希望这可以帮助!