1

So I have a client who does not allow any server side coding, except in rare occurences classic asp, so everything is HTML and javascript.

So basically I need to build a URL from the form and then redirect. Javascript isn't necessarily my thing, but this would take me 5 minutes in asp.net using String.Format.

Is there a String.Format method in javascript?

Jack Marchetti
  • 15,536
  • 14
  • 81
  • 117

3 Answers3

3

Ouch, that sucks.

Stolen from another post:

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;
}
Community
  • 1
  • 1
Jerod Venema
  • 44,124
  • 5
  • 66
  • 109
  • I think you mean String.prototype.format so that you can use it as "a {1} test".format("quick"); – AutomatedTester Dec 10 '09 at 18:17
  • Obviously he didn't mean that as the string is quite clearly the first argument but in most situations prototyping would be a better option. – Andy E Dec 10 '09 at 19:02
  • 1
    True, you could use prototyping. The reasoning here is simply that c# (my language of choice) works in this manner. Personal preference though, prototyping would work fine too. – Jerod Venema Dec 10 '09 at 21:10
0

no, there's no such thing in javascript, but some people have already written a printf for js

e.g JavaScript equivalent to printf/string.format

Community
  • 1
  • 1
user187291
  • 53,363
  • 19
  • 95
  • 127
0

I was looking for a similar thing and settled on Prototype's "Template" object.

From the Prototype examples



// the template (our formatting expression) var myTemplate = new Template( 'The TV show #{title} was created by #{author}.');

// our data to be formatted by the template var show = { title: 'The Simpsons', author: 'Matt Groening', network: 'FOX' };

// let's format our data myTemplate.evaluate(show); // -> "The TV show The Simpsons was created by Matt Groening."

mlo55
  • 6,663
  • 6
  • 33
  • 26