How can I add or update a query string parameter?

后端 未结 27 3206
别那么骄傲
别那么骄傲 2020-11-22 02:35

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

27条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 03:33

    It's so simple with URLSearchParams, supported in all modern browsers (caniuse).

    let p = new URLSearchParams();
    p.set("foo", "bar");
    p.set("name", "Jack & Jill?");
    console.log("http://example.com/?" + p.toString());

    If you want to modify the existing URL, construct the object like this: new URLSearchParams(window.location.search) and assign the string to window.location.search.

提交回复
热议问题