How can I add or update a query string parameter?

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

    This is my preference, and it covers the cases I can think of. Can anyone think of a way to reduce it to a single replace?

    function setParam(uri, key, val) {
        return uri
            .replace(RegExp("([?&]"+key+"(?=[=&#]|$)[^#&]*|(?=#|$))"), "&"+key+"="+encodeURIComponent(val))
            .replace(/^([^?&]+)&/, "$1?");
    }
    

提交回复
热议问题