On button click, I want to add query params. The problem is if I hit the button again, it is re-adding the values to URL. Is there a way for me to replace rather than add to?
My code:
$('#btn').on('click', function() {
let my_arr = arr.join('&');
window.history.replaceState({}, 'Title', `/${window.location.search}&${my_arr}`);
});
On first click if it adds my query params: a=1&b=2
.
If I click the button again with new values, it is re-adding the a=5&b=2
to the previous value making it look like: a=1&b=2&a=5&b=2
.
Is there a way for it to replace those values instead of adding to it?
Here is an example that also preserved existing values, only overwriting the ones that you specify.
$('#btn').on('click', function() {
const testFallbackValue = "?a=33&b=77&c=234"; // Just for demonstration
const searchParams = new URLSearchParams(window.location.search || testFallbackValue);
const myNewValue = {
a: 1,
b: 2,
};
Object.entries(myNewValue).forEach(([k, v]) => {
searchParams.set(k, v);
});
console.log(searchParams.toString());
// Uncomment when ready to replace state
//window.history.replaceState({}, 'Title', `/?${searchParams.toString()}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="btn">Click</button>
If you do not want to keep other existing values, you can also ignore passing the current search string to URLSearchParams constructor.