【问题标题】:Equivalent of String.format in jQuery等效于 jQuery 中的 String.format
【发布时间】:2009-06-24 14:30:36
【问题描述】:

我正在尝试将一些 JavaScript 代码从 MicrosoftAjax 移动到 JQuery。我在 MicrosoftAjax 中使用流行的 .net 方法的 JavaScript 等价物,例如String.format(), String.startsWith() 等。在jQuery中有没有它们的等价物?

【问题讨论】:

标签: javascript jquery string.format


【解决方案1】:

source code for ASP.NET AJAX is available 供您参考,因此您可以从中挑选,并将您想要继续使用的部分包含在单独的 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);
}

【讨论】:

  • 看起来没什么大不了的。显然,JavaScript 版本没有所有花哨的数字格式。 blog.stevex.net/index.php/string-formatting-in-csharp
  • 哇,我其实已经考虑过了,但也认为这是不可能的,因为许可证,不知道他们是在 Microsoft Permissive License 下发布的,非常感谢
  • 许可或无许可.. 写这么简单的东西只有一种正确的方法
  • 每次调用 format 时为每个参数构造(然后丢弃)RegEx 对象可能会使垃圾收集器负担过重。
  • 警告:这将递归格式化:所以如果你有{0}{1}{0} 将首先被替换,然后在已经替换的文本和原始格式中所有出现的{1}将被替换。
【解决方案2】:

这是 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;
};

用法:

'Added {0} by {1} to your collection'.f(title, artist)
'Your balance is {0} USD'.f(77.7) 

我经常使用它,所以我将其别名为 f,但您也可以使用更详细的 format。例如'Hello {0}!'.format(name)

【讨论】:

  • 现代浏览器有更简单的方法:stackoverflow.com/a/41052964/120296
  • @david 模板字符串根本不是一回事。它们是字符串连接的语法糖,很好但与格式化不同。它们立即运行,因此,替换必须在定义点的范围内。因此,您不能将它们存储在文本文件或数据库中。事实上,将它们存储在任何地方的唯一方法就是将它们放在一个函数中。格式化字符串函数采用不关心变量名称的位置替换。
【解决方案3】:

上述许多函数(除了 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 Mitchelmore 的另一个很好的实现,具有许多不错的额外功能:https://web.archive.org/web/20120315214858/http://blairmitchelmore.com/javascript/string.format

【讨论】:

【解决方案4】:

制作了一个将集合或数组作为参数的格式函数

用法:

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];
    });
};

【讨论】:

  • 不错,缺少的只是:String.prototype.format = function (col) {return format(this,col);}
  • 我不喜欢扩展字符串
  • 用法中有一个小错字:第二行应该是:format("i can speak {0} since i was {1}",'javascript',10);
  • 为什么不喜欢使用String.prototype扩展字符串?
【解决方案5】:

有一个(有点)官方选项:jQuery.validator.format

附带 jQuery Validation Plugin 1.6(至少)。
与 .NET 中的 String.Format 非常相似。

编辑修复了断开的链接。

【讨论】:

    【解决方案6】:

    如果您使用的是验证插件,您可以使用:

    jQuery.validator.format("{0} {1}", "cool", "formatting") = 'cool formatting'

    http://docs.jquery.com/Plugins/Validation/jQuery.validator.format#templateargumentargumentN...

    【讨论】:

    • JQuery 最小版本 ?
    【解决方案7】:

    虽然不完全符合 Q 的要求,但我构建了一个类似但使用命名占位符而不是编号的。我个人更喜欢使用命名参数,然后将一个对象作为参数发送给它(更冗长,但更易于维护)。

    String.prototype.format = function (args) {
        var newStr = this;
        for (var key in args) {
            newStr = newStr.replace('{' + key + '}', args[key]);
        }
        return newStr;
    }
    

    这是一个示例用法...

    alert("Hello {name}".format({ name: 'World' }));
    

    【讨论】:

      【解决方案8】:

      使用支持 EcmaScript 2015 (ES6) 的现代浏览器,您可以享受 Template Strings。您可以直接将变量值注入其中,而不是格式化:

      var name = "Waleed";
      var message = `Hello ${name}!`;
      

      请注意,模板字符串必须使用反引号 (`)。

      【讨论】:

        【解决方案9】:

        目前给出的答案都没有明显优化使用附件初始化一次并存储正则表达式,以供后续使用。

        // 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() 实现。

        【讨论】:

        • rx2 是不必要的,看我的实现;您在 rx1 中有(括号),但不要使用它们传递给内部函数的值。另外,我认为这是一个明显的优化在 Javascript 引擎中。您确定现代浏览器还没有在幕后进行这种优化吗? Perl 在 1990 年就这样做了。你说得对,应该有一个包装函数来检查它是否已经实现。
        • 此外,对 (args[idx] === "") 的测试对我来说似乎是多余的:它已经被该行的第一个测试覆盖,因为 undefined !== ""。
        【解决方案10】:

        已经过了赛季后期,但我一直在查看给出的答案,并获得了我的 tuppence 价值:

        用法:

        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
        

        【讨论】:

          【解决方案11】:

          这是我的:

          String.format = function(tokenised){
                  var args = arguments;
                  return tokenised.replace(/{[0-9]}/g, function(matched){
                      matched = matched.replace(/[{}]/g, "");
                      return args[parseInt(matched)+1];             
                  });
              }
          

          不是防弹的,但如果你明智地使用它,它就会起作用。

          【讨论】:

            【解决方案12】:

            现在你可以使用Template Literals

            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);

            【讨论】:

            • 我对模板文字感到很兴奋,直到我发现它们只有在字符串与替换变量一起定义时才有效。对我来说,这让它们几乎毫无用处;出于某种原因,我的大多数字符串都是与填充/使用它们的代码分开定义的。
            【解决方案13】:

            这是我的版本,它能够逃脱“{”,并清理那些未分配的占位符。

            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);
            }
            

            【讨论】:

              【解决方案14】:

              以下答案可能是最有效的,但需要注意的是仅适用于 1 对 1 的参数映射。这使用连接字符串的最快方式(类似于 stringbuilder:字符串数组,连接)。这是我自己的代码。不过可能需要更好的分隔符。

              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("");
              }
              

              像这样使用它:

              alert(String.format("<a href='~'>~</a>", ["one", "two"]));
              

              【讨论】:

              • 接受的答案是最好的答案。我给出了一个独特的答案,该答案在您希望尽可能提高效率(长循环)并且您拥有 1:1 args 映射的情况下很有用。更高效的因为 replace() 和 new Regex() 以及执行正则表达式肯定比单个 split() 使用更多的 CPU 周期。
              • 不需要-1。不,它并不广泛适用,但他是对的,这会稍微更有效率。现在,对于作者来说,一个架构问题:什么样的应用程序会在客户端处理如此庞大的数据集,以至于需要进行这种优化?
              • 好点迈克尔布莱克本。大多数情况可能都很好。就我而言,我正在处理大量数据(产品组中的产品变体,因此可能有数百个变体),我的观点是,由于用户通常打开许多浏览器选项卡,并且每个网站往往会占用大量 CPU我更喜欢这种实现以保持高效率。
              【解决方案15】:

              这违反了 DRY 原则,但它是一个简洁的解决方案:

              var button = '<a href="{link}" class="btn">{text}</a>';
              button = button.replace('{text}','Authorize on GitHub').replace('{link}', authorizeUrl);
              

              【讨论】:

                【解决方案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];
                   }
                </script>
                </body>
                </html>
                

                【讨论】:

                • 这对于 URI 来说很好,但对于一般用途,让一个字符串同时包含格式和组件是非常脆弱的。如果你的字符串包含逗号怎么办?
                【解决方案17】:

                我无法得到乔什·斯托多拉的答案,但以下内容对我有用。注意prototype 的规范。 (在 IE、FF、Chrome 和 Safari 上测试。):

                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;
                }
                

                s 确实应该是this克隆,以免成为破坏性方法,但这并不是真正必要的。

                【讨论】:

                • 这不是破坏性的方法。当使用 s.replace() 的返回值重新分配 s 时,它保持不变。
                【解决方案18】:

                扩展 adamJLev 的精彩回答 above,这里是 TypeScript 版本:

                // 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;
                };
                

                【讨论】:

                  【解决方案19】:

                  我有一个 plunker 将它添加到字符串原型中: string.format 它不仅与其他一些示例一样短,而且更加灵活。

                  用法类似于c#版本:

                  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
                  

                  另外,添加了对使用名称和对象属性的支持

                  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
                  

                  【讨论】:

                    【解决方案20】:

                    您也可以使用这样的替换来关闭数组。

                    var url = '/getElement/_/_/_'.replace(/_/g, (_ => this.ar[this.i++]).bind({ar: ["invoice", "id", 1337],i: 0}))
                    > '/getElement/invoice/id/1337
                    

                    或者你可以试试bind

                    '/getElement/_/_/_'.replace(/_/g, (function(_) {return this.ar[this.i++];}).bind({ar: ["invoice", "id", 1337],i: 0}))
                    

                    【讨论】:

                      【解决方案21】:
                      // 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;
                          }
                      }
                      

                      【讨论】:

                        猜你喜欢
                        • 1970-01-01
                        • 1970-01-01
                        • 2010-11-17
                        • 1970-01-01
                        • 2010-10-11
                        • 2010-09-16
                        • 2015-05-24
                        • 2021-12-09
                        相关资源
                        最近更新 更多