GibboK
GibboK

Reputation: 73908

javascript how to add a variable to a string

I'm using javascript and jquery, I have a string like

  var apiUrlAnswer = 'https://api.stackexchange.com/2.0/answers/{ids}?order=desc&sort=activity&site=stackoverflow';

I need replace the {ids} with a variable.

In C# is possible to use a method called

String.Format(https://api.stackexchange.com/2.0/answers/{0}?order=desc&sort=activity&site=stackoverflow, myVariable);

I would like to know if exist something similar in Javascript so I can avoid simple string concatenation.

Thanks for your help!

Upvotes: 3

Views: 583

Answers (5)

Chris Moutray
Chris Moutray

Reputation: 18349

Well here's a String.format (like c#); I've extended javascripts String object to include a format method like this:

String.format = function(stringToFormat, argsForFormat) {

    for (var i = 0; i < argsForFormat.length; i++) {
        var regex = new RegExp('\{(' + i + ')}', 'g');
        stringToFormat = stringToFormat.replace(regex, argsForFormat[i]);
    }

    return stringToFormat;    
};

You can call it like this

var args = [1, 'activity', 'stackoverflow', 'desc']   
var apiUrlAnswer = 'https://api.stackexchange.com/2.0/answers/{0}?order={3}&sort={1}&site={2}';
var apiUrlAnswer = String.format(apiUrlAnswer, args);

Or an inline version would look like this

var apiUrlAnswer = String.format('https://api.stackexchange.com/2.0/answers/{0}?order={3}&sort={1}&site={2}', [1, 'activity', 'stackoverflow', 'desc']);

and another example

String.format("http://{0}.{1}.com", ['www', 'stackoverflow']);

Upvotes: 3

Flash
Flash

Reputation: 16703

If you are doing this frequently, a more robust alternative to using a regex is to use a client side templating engine like mustache.js. I have used this successfully and it's quick and lightweight.

var view = {
  ids: "Andrew"
};

var output = Mustache.render("https://api.stackexchange.com/2.0/answers/{{ids}}?order=desc&sort=activity&site=stackoverflow", view);

This has the advantage of separating your data and presentation nicely.

Upvotes: 1

nnnnnn
nnnnnn

Reputation: 150010

Use the String .replace() method:

var apiUrlAnswer = 'https://api.stackexchange.com/2.0/answers/{ids}?order=desc&sort=activity&site=stackoverflow';

apiUrlAnswer = apiUrlAnswer.replace("{ids}", yourVariable);

// OR, if there might be more than one instance of '{ids}' use a regex:
apiUrlAnswer = apiUrlAnswer.replace(/\{ids\}/g, yourVariable);

Upvotes: 5

Alfred
Alfred

Reputation: 21386

Try

var id = 'your_id';
var apiUrlAnswer = 'https://api.stackexchange.com/2.0/answers/'+id+'?order=desc&sort=activity&site=stackoverflow';

Upvotes: 0

Sune Trudslev
Sune Trudslev

Reputation: 974

How about just using replace:

apiUrlAnswer = apiUrlAnswer.replace('{ids}', 'test');

Upvotes: 0

Related Questions