0

I'm trying to create a string format I have about 8 parameters. I want to do something like this shown below.

string.format("www.website.com?Id={0}&Name={1}", 2,Emma)

However I have tried in JavaScript and it doesn't work.

Could anyone help?

Thanks in advance!

user2864740
  • 60,010
  • 15
  • 145
  • 220
Gurpreet Kaur
  • 29
  • 1
  • 4
  • Because that's *not* a standard JavaScript function. One can't make up stuff and expect it work. Instead of blaming JavaScript ("Not Working"), start by searching for how to do the indented task and/or what the "Not Working" error (in the console) means. – user2864740 Jun 29 '15 at 21:01

2 Answers2

2

There is no format() method for Javascript string objects.

However, you can easily implement it yourself using the code provided by fearphage: JavaScript equivalent to printf/string.format

Community
  • 1
  • 1
Delgan
  • 18,571
  • 11
  • 90
  • 141
0

Supporting String.prototype.format():

String.prototype.format = function(){
  var args = arguments;
  return this.replace(/\{(\d+)\}/g, function(a, num){
    return args[num] || a
  })
}

var str = "www.website.com?Id={0}&Name={1}".format(2, "Emma");
alert(str)

If you are in an environment with ECMAScript ES6's support, you can use Template Strings:

var variables = [2, "Emma"];
var str = `www.website.com?Id=${variables[0]}&Name=${variables[1]}`;