0

I have a page with a url akin to domain.com/?a=1&b=2&.... I'd like to refresh the page but be able to change any of the given query string values or add it in if it isn't already there.

ie. If I wanted b=5 both /?a=1 and /?a=1&b=2 would become /?a=1&b=5

I believe I need to use the URLSearchParams class to set the query string and redirect (instead of refresh) to the new url but I'm having trouble working out how to combine all the parts to create the url.

1 Answer 1

1

If I understand you correctly, you have a page with a url like /?a=1&b=2 and you want to navigate to /?a=1&b=5 using JavaScript.

// grab the search query, parse it into a `URLSearchParams` set
const queryData = new URLSearchParams(window.location.search.slice(1))

// manipulate the parameters as desired
queryData.set("b", 5)

// assemble the new URL using the current URL as the base
const newUrl = new URL(window.location.href)
newUrl.search = queryData

// redirect to the new URL
window.location.href = newUrl
Sign up to request clarification or add additional context in comments.

2 Comments

// assemble the new URL using the current URL as the base const newUrl = new URL(window.location.href) newUrl.search = queryData This part exactly, thanks!
An 's' is missed.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.