With javascript how can I add a query string parameter to the url if not present or if it present, update the current value? I am using jquery for my client side development.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
I wrote the following function which accomplishes what I want to achieve:
The URLSearchParams utility can be useful for this in combination with
window.location.search
. For example:Now
foo
has been set tobar
regardless of whether or not it already existed.However, the above assignment to
window.location.search
will cause a page load, so if that's not desirable use the History API as follows:Now you don't need to write your own regex or logic to handle the possible existence of query strings.
However, browser support is poor as it's currently experimental and only in use in recent versions of Chrome, Firefox, Safari, iOS Safari, Android Browser, Android Chrome and Opera. Use with a polyfill if you do decide to use it.
Update: Browser support has improved since my original answer.
Use this function to add, remove and modify query string parameter from URL based on jquery
Add new and modify existing parameter to url
Remove existing
If it's not set or want to update with a new value you can use:
This is in simple Javascript, by the way.
EDIT
You may want to try using the jquery query-object plugin
This should serve the purpose:
window.location.search is read/write.
However - modifying the query string will redirect the page you're on and cause a refresh from the server.
If what you're attempting to do is maintain client side state (and potentially make it bookmark-able), you'll want to modify the URL hash instead of the query string, which keeps you on the same page (window.location.hash is read/write). This is how web sites like twitter.com do this.
You'll also want the back button to work, you'll have to bind javascript events to the hash change event, a good plugin for that is http://benalman.com/projects/jquery-hashchange-plugin/