JavaScript equivalent to printf/String.Format

前端 未结 30 2492
囚心锁ツ
囚心锁ツ 2020-11-21 04:27

I\'m looking for a good JavaScript equivalent of the C/PHP printf() or for C#/Java programmers, String.Format() (IFormatProvider for .

相关标签:
30条回答
  • 2020-11-21 05:24

    The PHPJS project has written JavaScript implementations for many of PHP's functions. Since PHP's sprintf() function is basically the same as C's printf(), their JavaScript implementation of it should satisfy your needs.

    0 讨论(0)
  • 2020-11-21 05:25

    I use this simple function:

    String.prototype.format = function() {
        var formatted = this;
        for( var arg in arguments ) {
            formatted = formatted.replace("{" + arg + "}", arguments[arg]);
        }
        return formatted;
    };
    

    That's very similar to string.format:

    "{0} is dead, but {1} is alive!".format("ASP", "ASP.NET")
    
    0 讨论(0)
  • 2020-11-21 05:25

    I use this one:

    String.prototype.format = function() {
        var newStr = this, i = 0;
        while (/%s/.test(newStr))
            newStr = newStr.replace("%s", arguments[i++])
    
        return newStr;
    }
    

    Then I call it:

    "<h1>%s</h1><p>%s</p>".format("Header", "Just a test!");
    
    0 讨论(0)
  • 2020-11-21 05:27

    I'll add my own discoveries which I've found since I asked:

    • number_format (for thousand separator/currency formatting)
    • sprintf (same author as above)

    Sadly it seems sprintf doesn't handle thousand separator formatting like .NET's string format.

    0 讨论(0)
  • 2020-11-21 05:27

    Just in case someone needs a function to prevent polluting global scope, here is the function that does the same:

      function _format (str, arr) {
        return str.replace(/{(\d+)}/g, function (match, number) {
          return typeof arr[number] != 'undefined' ? arr[number] : match;
        });
      };
    
    0 讨论(0)
  • 2020-11-21 05:28

    I have a solution very close to Peter's, but it deals with number and object case.

    if (!String.prototype.format) {
      String.prototype.format = function() {
        var args;
        args = arguments;
        if (args.length === 1 && args[0] !== null && typeof args[0] === 'object') {
          args = args[0];
        }
        return this.replace(/{([^}]*)}/g, function(match, key) {
          return (typeof args[key] !== "undefined" ? args[key] : match);
        });
      };
    }
    

    Maybe it could be even better to deal with the all deeps cases, but for my needs this is just fine.

    "This is an example from {name}".format({name:"Blaine"});
    "This is an example from {0}".format("Blaine");
    

    PS: This function is very cool if you are using translations in templates frameworks like AngularJS:

    <h1> {{('hello-message'|translate).format(user)}} <h1>
    <h1> {{('hello-by-name'|translate).format( user ? user.name : 'You' )}} <h1>
    

    Where the en.json is something like

    {
        "hello-message": "Hello {name}, welcome.",
        "hello-by-name": "Hello {0}, welcome."
    }
    
    0 讨论(0)
提交回复
热议问题