代码之家  ›  专栏  ›  技术社区  ›  Waleed Eissa

与jQuery中的String.format等效

  •  188
  • Waleed Eissa  · 技术社区  · 16 年前

    20 回复  |  直到 10 年前
        1
  •  193
  •   Josh Stodola    16 年前

    这个 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和Starts。。。

    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);
    }
    
        2
  •  152
  •   adamJLev    13 年前

    这是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)

        3
  •  131
  •   andynormancx    11 年前

    上述许多函数(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
  •  50
  •   ianj    14 年前

    创建了一个格式函数,该函数将集合或数组作为参数

    用法:

    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];
        });
    };
    
        5
  •  36
  •   rsenna    11 年前

    有一个(某种程度上)官方选项: jQuery.validator.format


    非常类似于 String.Format

    编辑 修复了断开的链接。

        6
  •  17
  •   tusar    13 年前

    如果您正在使用验证插件,则可以使用:

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

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

        7
  •  13
  •   skolima    14 年前

    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
  •  10
  •   david    8 年前

    使用支持EcmaScript 2015(ES6)的现代浏览器,您可以享受 Template Strings

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

        9
  •  6
  •   user182669 user182669    14 年前

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

        10
  •  6
  •   RickL    8 年前

    虽然已经过了赛季末,但我只是看看给出的答案,我的一便士值多少钱:

    用法:

    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
  •  4
  •   Julian Jelfs    14 年前

    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
  •  3
  •   Arek Kostrzeba    9 年前

    现在你可以使用 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
  •  2
  •   Feng    14 年前

    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
  •  2
  •   Skystrider    11 年前

    下面的答案可能是最有效的,但需要注意的是,它只适用于参数的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"]));
    
        15
  •  2
  •   ilyaigpetrov    10 年前

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

    var button = '<a href="{link}" class="btn">{text}</a>';
    button = button.replace('{text}','Authorize on GitHub').replace('{link}', authorizeUrl);
    
        16
  •  0
  •   bensiu CandorZ    12 年前
    <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>
    
        17
  •  0
  •   Skystrider    11 年前

    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

        18
  •  0
  •   Community CDub    8 年前

    扩展adamJLev的伟大答案 above

    // 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
  •  0
  •   ShrapNull    10 年前

    我有一个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
  •  0
  •   test30    9 年前

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

    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
  •  0
  •   cskwg    4 年前
    // 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;
        }
    }