JavaScript equivalent to printf/String.Format

前端 未结 30 2424
囚心锁ツ
囚心锁ツ 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: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:

    {{('hello-message'|translate).format(user)}}

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

    Where the en.json is something like

    {
        "hello-message": "Hello {name}, welcome.",
        "hello-by-name": "Hello {0}, welcome."
    }
    

提交回复
热议问题