0

My URL is:

http://localhost:3000/?sort=rating

The parameter sort is dynamic, and I would like to add it to another URL.

In my javascript I have:

window.location.pathname + '.js?page=' + currentPage

How do I add the sort parameter at the end?

Example:

window.location.pathname + '.js?page=' + currentPage + &sortparam

In this case it would be:

window.location.pathname + '.js?page=' + currentPage + '&sort=rating'
Hannele
  • 9,301
  • 6
  • 48
  • 68
Rails beginner
  • 14,321
  • 35
  • 137
  • 257

3 Answers3

2

Here is what you're looking for:

How can I get query string values in JavaScript?

In your case:

function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.search);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

var sortparam = getParameterByName("sort");
window.location.pathname + '.js?page=' + currentPage + '&sort='+sortparam
Community
  • 1
  • 1
Johannes Staehlin
  • 3,680
  • 7
  • 36
  • 50
1

Here's one more, with a slightly more general wrapper:

function getParams() {

  var params = window.location.search.substring(1).split('& '),
    i = 0,
    pair = null,
    result = {};

  while (pair = params[i++]) {
    pair = pair.split('=');
    result[pair[0]] = decodeURIComponent(pair[1]);
  }

  return result;
}

alert(getParams().page);
rjz
  • 16,182
  • 3
  • 36
  • 35
0
window.location.pathname + '.js?page=' + currentPage +
    "&" + location.search.match(/(sort=.*?)&|$/)[1]
kirilloid
  • 14,011
  • 6
  • 38
  • 52