Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 893
GibboK Avatar asked Mar 12 '26 00:03

GibboK


1 Answers

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);
like image 144
nnnnnn Avatar answered Mar 14 '26 14:03

nnnnnn