How can I add or update a query string parameter?

后端 未结 27 2891
别那么骄傲
别那么骄傲 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

    Update (2020): URLSearchParams is now supported by all modern browsers.

    The URLSearchParams utility can be useful for this in combination with window.location.search. For example:

    if ('URLSearchParams' in window) {
        var searchParams = new URLSearchParams(window.location.search);
        searchParams.set("foo", "bar");
        window.location.search = searchParams.toString();
    }
    

    Now foo has been set to bar regardless of whether or not it already existed.

    However, the above assignment to window.location.search will cause a page load, so if that's not desirable use the History API as follows:

    if ('URLSearchParams' in window) {
        var searchParams = new URLSearchParams(window.location.search)
        searchParams.set("foo", "bar");
        var newRelativePathQuery = window.location.pathname + '?' + searchParams.toString();
        history.pushState(null, '', newRelativePathQuery);
    }
    

    Now you don't need to write your own regex or logic to handle the possible existence of query strings.

    However, browser support is poor as it's currently experimental and only in use in recent versions of Chrome, Firefox, Safari, iOS Safari, Android Browser, Android Chrome and Opera. Use with a polyfill if you do decide to use it.

提交回复
热议问题