user1447679
user1447679

Reputation: 3270

How to insert javascript variables into a URL

var a = 1;
var b = 2;
var mylink = "http://website.com/page.aspx?list=' + a + '&sublist=' + b + '";

This doesn't work. Is there a simple way to insert these other variables into the url query?

Upvotes: 12

Views: 54561

Answers (3)

Vineesh TP
Vineesh TP

Reputation: 7973

var a = 1;
var b = 2;
var mylink = `http://website.com/page.aspx?list=${a}&sublist=${b}`;

Copied from above answer.

Do notice that it is not single quote.

enter image description here

Upvotes: 4

Skotee
Skotee

Reputation: 880

In modern JavaScript standards we are using ${var} :

var a = 1;
var b = 2;
var mylink = `http://website.com/page.aspx?list=${a}&sublist=${b}`;

Upvotes: 4

adeneo
adeneo

Reputation: 318342

By using the right quotes:

var a = 1;
var b = 2;
var mylink = "http://website.com/page.aspx?list=" + a + "&sublist=" + b;

If you start a string with doublequotes, it can be ended with doublequotes and can contain singlequotes, same goes for the other way around.

Upvotes: 30

Related Questions