Jack Marchetti
Jack Marchetti

Reputation: 15754

Is there a way to do String.Format() in javascript?

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?

Upvotes: 2

Views: 2917

Answers (3)

mlo55
mlo55

Reputation: 6915

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."

Upvotes: 0

Jerod Venema
Jerod Venema

Reputation: 44642

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

Upvotes: 4

user187291
user187291

Reputation: 53940

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

Upvotes: 0

Related Questions