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
To give an code example for modifying
window.location.search
as suggested by Gal and tradyblix:Based on the answer @ellemayo gave, I came up with the following solution that allows for disabling of the hash tag if desired:
Call it like this:
Results in:
A different approach without using regular expressions. Supports 'hash' anchors at the end of the url as well as multiple question mark charcters (?). Should be slightly faster than the regular expression approach.
There are a lot of awkward and unnecessarily complicated answers on this page. The highest rated one, @amateur's, is quite good, although it has a bit of unnecessary fluff in the RegExp. Here is a slightly more optimal solution with cleaner RegExp and a cleaner
replace
call:As an added bonus, if
uri
is not a string, you won't get errors for trying to callmatch
orreplace
on something that may not implement those methods.And if you want to handle the case of a hash (and you've already done a check for properly formatted HTML), you can leverage the existing function instead of writing a new function containing the same logic:
Or you can make some slight changes to @Adam's otherwise excellent answer:
Here is my library to do that: https://github.com/Mikhus/jsurl
This is my preference, and it covers the cases I can think of. Can anyone think of a way to reduce it to a single replace?