1

Using js function in JavaScript equivalent to printf/string.format

if (!String.prototype.format) {
    String.prototype.format = function () {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function (match, number) {
            return typeof args[number] != 'undefined'
              ? args[number]
              : match
            ;
        });
    };
}

Trying to pass delimited fields as a parameter to this function argument. using split to create array and pass it as argument but does not seem to work

    var str =" this is a {0} test in {1}";
 var args = "StringFormat|Javascript";
 var return = str.format(args.split("|"));

actual: this is a StringFormat|Javascript test in {1}

expected: this is a StringFormat test in Javascript

Community
  • 1
  • 1
Justin Homes
  • 3,739
  • 9
  • 49
  • 78

1 Answers1

1

It's because .format() is not looking for an array of strings, just a string. So this is how you should be calling .format() for dynamic arrays per Paolo's suggestion :

var str =" this is a {0} test in {1}";
var args = "StringFormat|Javascript".split("|");
var return = str.format.apply(str, args);
Adjit
  • 10,134
  • 12
  • 53
  • 98
  • but my args will have dynamic number of pipes. its not fixed. – Justin Homes Jun 28 '14 at 20:54
  • 1
    [`Function.prototype.apply`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) would be a better choice. Something like: `str.format.apply(str, args)` – Paolo Moretti Jun 28 '14 at 20:55
  • @JustinHomes Paolo is correct, that is how you should call it if it is dynamic. – Adjit Jun 28 '14 at 20:59