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 
5
  • Possible duplicate of Updating existing URL querystring values with jQuery Commented Feb 21, 2017 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. Commented Feb 21, 2017 at 21:05
  • Also possible duplicate of add or update query string parameter Commented Feb 21, 2017 at 21:08
  • Possible duplicate of add or update query string parameter Commented Feb 21, 2017 at 21:10
  • Thanks @MikeMcCaughan for your valuable comments. The accepted answer is what I am looking for. Commented Feb 21, 2017 at 21:31

1 Answer 1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.