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
asked Feb 21, 2017 at 20:52
user5084534user5084534
-
Possible duplicate of Updating existing URL querystring values with jQueryHeretic Monkey– Heretic Monkey2017年02月21日 21:04:57 +00:00Commented Feb 21, 2017 at 21:04
-
2If 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– Heretic Monkey2017年02月21日 21:05:48 +00:00Commented Feb 21, 2017 at 21:05
-
Also possible duplicate of add or update query string parameterAdam– Adam2017年02月21日 21:08:10 +00:00Commented Feb 21, 2017 at 21:08
-
Possible duplicate of add or update query string parameterAdam– Adam2017年02月21日 21:10:58 +00:00Commented Feb 21, 2017 at 21:10
-
Thanks @MikeMcCaughan for your valuable comments. The accepted answer is what I am looking for.user5084534– user50845342017年02月21日 21:31:46 +00:00Commented Feb 21, 2017 at 21:31
1 Answer 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
answered Feb 21, 2017 at 21:13
Comments
lang-js