0

Possible Duplicate:
JavaScript equivalent to printf/string.format

Do we have something like C# String.Format(...) in JavaScript?

I like to be able to say String.Format('text text {0}, text text {1}', value1, value2);

and ideally as an extension method:

'text text {0}, text text {1}'.format(value1, value2);

Thanks,

0

1 Answer 1

4

here is your solution:

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

more informations here => Equivalent of String.format in jQuery

Sign up to request clarification or add additional context in comments.

3 Comments

How is it possible to have the format method as an extension method of the string instance? e.g. accessing it with "text {0} text {1}".format(value1, value2); the benefit is having less code.
How to use the above code in the same way as I use extension methods in C#?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.