Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

javascript - Updating existing URL querystring values with jQuery

Let's say I have a url such as:

http://www.example.com/hello.png?w=100&h=100&bg=white

What I'd like to do is update the values of the w and h querystring, but leave the bg querystring intact, for example:

http://www.example.com/hello.png?w=200&h=200&bg=white

So what's the fastest most efficient way to read the querystring values (and they could be any set of querystring values, not just w, h, and bg), update a few or none of the values, and return the full url with the new querystring?

So:

  1. Get the values of each querystring key
  2. Update any number of the keys
  3. Rebuild the url with the new values
  4. Keep all of the other values which weren't updated
  5. It will not have a standard set of known keys, it could change per URL
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Simple solution

You can use URLSearchParams.set() like below:

var currentUrl = 'http://www.example.com/hello.png?w=100&h=100&bg=white';
var url = new URL(currentUrl);
url.searchParams.set("w", "200"); // setting your param
var newUrl = url.href; 
console.log(newUrl);

Online demo (jsfiddle)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...