0

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

5
  • 1
    Not working how? Remember to include text in URLs they must be encoded. See stackoverflow.com/questions/8135132/… Commented Nov 22, 2024 at 16:41
  • 2
    You haven't concatenated your strings correctly. Commented Nov 22, 2024 at 16:42
  • @evolutionxbox It's not about encoding, it's about the proper syntax to concatenate variables. Although encoding could be a problem if there are special characters in the variables. Commented Nov 22, 2024 at 17:14
  • How I concatenate, this is the question.. I tried many ways with single quote, double quote and backticks but nothing works. Commented Nov 24, 2024 at 14:28
  • Your example uses single quotes, but you neglected to use the concatenation operator, '+. If you wish to use backticks, then you need to use ${variableName}. Commented Nov 24, 2024 at 22:46

1 Answer 1

4

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';
Sign up to request clarification or add additional context in comments.

2 Comments

There is also new URLSearchParams(paramsString) See: developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
works like a charm.. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.