javascripturlparametersquery-string

How to use javascript variables in URL as querystring parameters


I want to use javascript variables in URL as querystring parameters. what is correct way?

 var fromSemester = document.getElementById('<%= newFromSemesterValue.ClientID%>').value;
 var toSemester = document.getElementById('<%= newToSemesterValue.ClientID%>').value;

I wan to use fromSemester and toSemester variables in URL as querystring parameters like below: But javascript throws en error. What is the correct way to use VAR variables inside URL?

var url = 'MyPage.aspx?id=2&fromsemester='fromSemester'&tosemester='toSemester'&language=eng'

But this URL is not working


Solution

  • There are several options; the simplest is probably to use the URL class:

    const url = new URL('MyPage.aspx?id=2&language=eng', location.href);
    url.searchParams.set("fromsemester", fromSemester);
    url.searchParams.set("tosemester", toSemester);
    

    Alternatively, string interpolation:

    const url = `MyPage.aspx?id=2&fromsemester=${encodeURIComponent(fromSemester)}&tosemester=${encodeURIComponent(toSemester)}&language=eng`;
    

    Or as a last resort, string concatenation:

    const url = 'MyPage.aspx?id=2&fromsemester=' 
        + encodeURIComponent(fromSemester) 
        + '&tosemester=' 
        + encodeURIComponent(toSemester) 
        + '&language=eng';