How to insert javascript variables into a URL

后端 未结 3 1639
终归单人心
终归单人心 2020-12-31 11:45
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

相关标签:
3条回答
  • 2020-12-31 11:53
    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.

    0 讨论(0)
  • 2020-12-31 11:57

    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.

    0 讨论(0)
  • 2020-12-31 12:18

    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}`;
    
    0 讨论(0)
提交回复
热议问题