0

I know this question is asked many times but none of these solutions worked for me.

What I need to do is to replace the url query string with some other value.

I need to replace ?tab= from URL. Thats my requirement.

URL:

http://localhost:3000/private_search/search_all?tab=playlists&term=phy&utf8=✓&
rating[]=4&_=1487710144036

I need to make it:

http://localhost:3000/private_search/search_all?tab=featured&term=phy&utf8=✓&rating[]=4&_=1487710144036

http://localhost:3000/private_search/search_all?tab=all_schools&term=phy&
utf8=✓&rating[]=4&_=1487710144036

decodeURIComponent(this.url) returns:

http://localhost:3000/private_search/search_all?tab=playlists&term=phy&utf8=✓&
rating[]=4&_=1487710144036


$("#featured-url").attr('href', decodeURIComponent(this.url)); // need to change url here 
 $("#school-url").attr('href', decodeURIComponent(this.url));  // need to change url here 
  • Possible duplicate of [Updating existing URL querystring values with jQuery](http://stackoverflow.com/questions/9622207/updating-existing-url-querystring-values-with-jquery) – Heretic Monkey Feb 21 '17 at 21:04
  • 2
    If any of the solutions presented on the above duplicate do not work for you, [edit] your question to include how you implemented them and what didn't work when you tried them. – Heretic Monkey Feb 21 '17 at 21:05
  • Also possible duplicate of [add or update query string parameter](http://stackoverflow.com/questions/5999118/add-or-update-query-string-parameter) – Adam Feb 21 '17 at 21:08
  • Possible duplicate of [add or update query string parameter](http://stackoverflow.com/questions/5999118/add-or-update-query-string-parameter) – Adam Feb 21 '17 at 21:10
  • Thanks @MikeMcCaughan for your valuable comments. The accepted answer is what I am looking for. –  Feb 21 '17 at 21:31

1 Answers1

1

Regular Expression is extremely powerful and perfect for these sorts of situations, but difficult to learn. This is how to use it in your example.

$("#featured-url").attr('href',
  $("#featured-url").attr('href').replace(/\?tab=[^&]+/, '?tab=featured')
);

$("#school-url").attr('href',
  $("#school-url").attr('href').replace(/\?tab=[^&]+/, '?tab=all_schools')
);

Here's an explanation of the RegEx:

  • \? matches the ? character (escaped, since ? has other meanings)
  • tab= matches that string of characters
  • [^&] matches anything except an &
  • + expects there to be one or more of the previous match
Gwellin
  • 474
  • 1
  • 4
  • 8