Reputation: 73908
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
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
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
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
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
Reputation: 974
How about just using replace:
apiUrlAnswer = apiUrlAnswer.replace('{ids}', 'test');
Upvotes: 0