如何用 javascript/jquery 替换 url 参数?

发布于 2024-11-30 21:06:51 字数 312 浏览 2 评论 0 原文

我一直在寻找一种有效的方法来做到这一点,但一直找不到它,基本上我需要的是给定这个网址,例如:

http://localhost/mysite/includes/phpThumb.php?src=http://media2.jupix.co.uk/v3/clients/4/properties/795/IMG_795_1_large.jpg&w=592&aoe=1&q=100

我希望能够更改 中的网址使用 javascript 或 jquery 将 src 参数与另一个值一起使用,这可能吗?

I've been looking for an efficient way to do this but haven't been able to find it, basically what I need is that given this url for example:

http://localhost/mysite/includes/phpThumb.php?src=http://media2.jupix.co.uk/v3/clients/4/properties/795/IMG_795_1_large.jpg&w=592&aoe=1&q=100

I'd like to be able to change the URL in the src parameter with another value using javascript or jquery, is this possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

永言不败 2024-12-07 21:06:51

以下解决方案结合了其他答案并处理一些特殊情况:

  • 参数在原始 url 中不存在 参数
  • 是唯一参数 参数
  • 是第一个或最后
  • 一个 新参数值与旧参数值相同
  • url 以 ? 字符
  • \b 确保另一个以 paramName 结尾的参数不会匹配

解决方案:

function replaceUrlParam(url, paramName, paramValue)
{
    if (paramValue == null) {
        paramValue = '';
    }
    var pattern = new RegExp('\\b('+paramName+'=).*?(&|#|$)');
    if (url.search(pattern)>=0) {
        return url.replace(pattern,'$1' + paramValue + '$2');
    }
    url = url.replace(/[?#]$/,'');
    return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
}

已知限制:

  • 不会通过将 paramValue 设置为 null 来清除参数,相反,它将其设置为空字符串。如果您想删除该参数,请参阅 https://stackoverflow.com/a/25214672

The following solution combines other answers and handles some special cases:

  • The parameter does not exist in the original url
  • The parameter is the only parameter
  • The parameter is first or last
  • The new parameter value is the same as the old
  • The url ends with a ? character
  • \b ensures another parameter ending with paramName won't be matched

Solution:

function replaceUrlParam(url, paramName, paramValue)
{
    if (paramValue == null) {
        paramValue = '';
    }
    var pattern = new RegExp('\\b('+paramName+'=).*?(&|#|$)');
    if (url.search(pattern)>=0) {
        return url.replace(pattern,'$1' + paramValue + '$2');
    }
    url = url.replace(/[?#]$/,'');
    return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
}

Known limitations:

∝单色的世界 2024-12-07 21:06:51

如今,使用原生 JS 就可以实现这一点

var href = new URL('https://google.com?q=cats');
href.searchParams.set('q', 'dogs');
console.log(href.toString()); // https://google.com/?q=dogs

Nowdays that's possible with native JS

var href = new URL('https://google.com?q=cats');
href.searchParams.set('q', 'dogs');
console.log(href.toString()); // https://google.com/?q=dogs
宛菡 2024-12-07 21:06:51

这不是更好的解决方案吗?

var text = 'http://localhost/mysite/includes/phpThumb.php?src=http://media2.jupix.co.uk/v3/clients/4/properties/795/IMG_795_1_large.jpg&w=592&aoe=1&q=100';
var newSrc = 'www.google.com';
var newText = text.replace(/(src=).*?(&)/,'$1' + newSrc + '$2');

编辑:

在代码中增加了一些清晰度,并在生成的链接中保留“src”

$1 表示 () 中的第一部分(即)src=$2 代表 () 中的第二部分(即 &),因此这表明您将更改 之间的值>src 和<代码>&。更清楚的是,它应该是这样的:

src='changed value'& // this is to be replaced with your original url

用于替换所有出现的ADD-ON:

如果您有多个同名参数,您可以附加到正则表达式全局标志,就像这样 text.replace(/(src= ).*?(&)/g,'$1' + newSrc + '$2'); 这将替换那些共享相同名称的参数的所有值。

Wouldn't this be a better solution?

var text = 'http://localhost/mysite/includes/phpThumb.php?src=http://media2.jupix.co.uk/v3/clients/4/properties/795/IMG_795_1_large.jpg&w=592&aoe=1&q=100';
var newSrc = 'www.google.com';
var newText = text.replace(/(src=).*?(&)/,'$1' + newSrc + '$2');

EDIT:

added some clarity in code and kept 'src' in the resulting link

$1 represents first part within the () (i.e) src= and $2 represents the second part within the () (i.e) &, so this indicates you are going to change the value between src and &. More clear, it should be like this:

src='changed value'& // this is to be replaced with your original url

ADD-ON for replacing all the ocurrences:

If you have several parameters with the same name, you can append to the regex global flag, like this text.replace(/(src=).*?(&)/g,'$1' + newSrc + '$2'); and that will replaces all the values for those params that shares the same name.

千仐 2024-12-07 21:06:51

Javascript 现在提供了一个非常有用的功能来处理 url 参数: URLSearchParams

var searchParams = new URLSearchParams(window.location.search);
searchParams.set('src','newSrc')
var newParams = searchParams.toString()

Javascript now give a very useful functionnality to handle url parameters: URLSearchParams

var searchParams = new URLSearchParams(window.location.search);
searchParams.set('src','newSrc')
var newParams = searchParams.toString()
你曾走过我的故事 2024-12-07 21:06:51

在现代浏览器(除了 IE9 及更低版本的所有浏览器)中,有了 新 URL api

var url = new window.URL(document.location); // fx. http://host.com/endpoint?abc=123
url.searchParams.set("foo", "bar");
console.log(url.toString()); // http://host/endpoint?abc=123&foo=bar
url.searchParams.set("foo", "ooft");
console.log(url.toString()); // http://host/endpoint?abc=123&foo=ooft

In modern browsers (everything except IE9 and below), our lives are a little easier now with the new URL api

var url = new window.URL(document.location); // fx. http://host.com/endpoint?abc=123
url.searchParams.set("foo", "bar");
console.log(url.toString()); // http://host/endpoint?abc=123&foo=bar
url.searchParams.set("foo", "ooft");
console.log(url.toString()); // http://host/endpoint?abc=123&foo=ooft
笙痞 2024-12-07 21:06:51
// Construct URLSearchParams object instance from current URL querystring.
var queryParams = new URLSearchParams(window.location.search);
 
// Set new or modify existing parameter value. 
queryParams.set("myParam", "myValue");
 
// Replace current querystring with the new one.
history.replaceState(null, null, "?"+queryParams.toString());

或者,我们可以使用 pushState() 方法创建一个新历史条目,而不是使用 ReplaceState() 修改当前历史条目:

history.pushState(null, null, "?"+queryParams.toString());
// Construct URLSearchParams object instance from current URL querystring.
var queryParams = new URLSearchParams(window.location.search);
 
// Set new or modify existing parameter value. 
queryParams.set("myParam", "myValue");
 
// Replace current querystring with the new one.
history.replaceState(null, null, "?"+queryParams.toString());

Alternatively instead of modifying current history entry using replaceState() we can use pushState() method to create a new one:

history.pushState(null, null, "?"+queryParams.toString());
痴梦一场 2024-12-07 21:06:51

这是修改后的 stenix 代码,它并不完美,但它可以处理 url 中包含提供参数的参数的情况,例如:

/search?searchquery=text and 'query' is provided.

在这种情况下,searchquery 参数值已更改。

代码:

function replaceUrlParam(url, paramName, paramValue){
    var pattern = new RegExp('(\\?|\\&)('+paramName+'=).*?(&|$)')
    var newUrl=url
    if(url.search(pattern)>=0){
        newUrl = url.replace(pattern,'$1$2' + paramValue + '$3');
    }
    else{
        newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
    }
    return newUrl
}

Here is modified stenix's code, it's not perfect but it handles cases where there is a param in url that contains provided parameter, like:

/search?searchquery=text and 'query' is provided.

In this case searchquery param value is changed.

Code:

function replaceUrlParam(url, paramName, paramValue){
    var pattern = new RegExp('(\\?|\\&)('+paramName+'=).*?(&|$)')
    var newUrl=url
    if(url.search(pattern)>=0){
        newUrl = url.replace(pattern,'$1$2' + paramValue + '$3');
    }
    else{
        newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
    }
    return newUrl
}
離人涙 2024-12-07 21:06:51

如果您有非常狭窄且具体的用例,例如用某些特殊字符替换给定名称的特定参数(其字母数字值上限为一定的长度限制),您可以尝试这种方法:

urlValue.replace(/\bsrc=[0-9a-zA-Z_@.#+-]{1,50}\b/, 'src=' + newValue);

示例:

let urlValue = 'www.example.com?a=b&src=test-value&p=q';
const newValue = 'sucess';
console.log(urlValue.replace(/\bsrc=[0-9a-zA-Z_@.#+-]{1,50}\b/, 'src=' + newValue));
// output - www.example.com?a=b&src=sucess&p=q

If you are having very narrow and specific use-case like replacing a particular parameter of given name that have alpha-numeric values with certain special characters capped upto certain length limit, you could try this approach:

urlValue.replace(/\bsrc=[0-9a-zA-Z_@.#+-]{1,50}\b/, 'src=' + newValue);

Example:

let urlValue = 'www.example.com?a=b&src=test-value&p=q';
const newValue = 'sucess';
console.log(urlValue.replace(/\bsrc=[0-9a-zA-Z_@.#+-]{1,50}\b/, 'src=' + newValue));
// output - www.example.com?a=b&src=sucess&p=q
悲凉≈ 2024-12-07 21:06:51

我已经找到了替换 URL 参数的最佳解决方案。

以下函数会将以下 URL 中的房间值替换为 3。

http://example.com/property/? min=50000&max=60000&room=1&property_type=House

var newurl = replaceUrlParam('room','3');
history.pushState(null, null, newurl);

function replaceUrlParam(paramName, paramValue){
    var url = window.location.href;

    if (paramValue == null) {
        paramValue = '';
    }

    var pattern = new RegExp('\\b('+paramName+'=).*?(&|#|$)');
    if (url.search(pattern)>=0) {
        return url.replace(pattern,'$1' + paramValue + '$2');
    }

    url = url.replace(/[?#]$/,'');
    return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
}

输出

http://example.com/property/?min=50000&max=60000&room=3&property_type=House

I have get best solution to replace the URL parameter.

Following function will replace room value to 3 in the following URL.

http://example.com/property/?min=50000&max=60000&room=1&property_type=House

var newurl = replaceUrlParam('room','3');
history.pushState(null, null, newurl);

function replaceUrlParam(paramName, paramValue){
    var url = window.location.href;

    if (paramValue == null) {
        paramValue = '';
    }

    var pattern = new RegExp('\\b('+paramName+'=).*?(&|#|$)');
    if (url.search(pattern)>=0) {
        return url.replace(pattern,'$1' + paramValue + '$2');
    }

    url = url.replace(/[?#]$/,'');
    return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
}

Output

http://example.com/property/?min=50000&max=60000&room=3&property_type=House

不知在何时 2024-12-07 21:06:51

编辑参数
URLSearchParams 对象的 set 方法设置参数的新值。

设置新值后,您可以使用 toString() 方法获取新的查询字符串。该查询字符串可以设置为 URL 对象的搜索属性的新值。

然后可以使用 URL 对象的 toString() 方法检索最终的新 url。


var query_string = url.search;

var search_params = new URLSearchParams(query_string); 

// new value of "id" is set to "101"
search_params.set('id', '101');

// change the search property of the main url
url.search = search_params.toString();

// the new url string
var new_url = url.toString();

// output : http://demourl.com/path?id=101&topic=main
console.log(new_url);

来源 - https://usefulangle.com/post/81/javascript-change- url 参数

Editing a Parameter
The set method of the URLSearchParams object sets the new value of the parameter.

After setting the new value you can get the new query string with the toString() method. This query string can be set as the new value of the search property of the URL object.

The final new url can then be retrieved with the toString() method of the URL object.


var query_string = url.search;

var search_params = new URLSearchParams(query_string); 

// new value of "id" is set to "101"
search_params.set('id', '101');

// change the search property of the main url
url.search = search_params.toString();

// the new url string
var new_url = url.toString();

// output : http://demourl.com/path?id=101&topic=main
console.log(new_url);

Source - https://usefulangle.com/post/81/javascript-change-url-parameters

昨迟人 2024-12-07 21:06:51

UpdatE:使它成为一个对你来说很好的功能: http://jsfiddle.net/wesbos/KH25r/1 /

function swapOutSource(url, newSource) {
    params = url.split('&');
    var src = params[0].split('=');
    params.shift();
    src[1] = newSource;
    var newUrl = ( src.join('=') + params.join('&')); 
    return newUrl; 
}

那就去做吧!

var newUrl = swapOutSource("http://localhost/mysite/includes/phpThumb.php?src=http://media2.jupix.co.uk/v3/clients/4/properties/795/IMG_795_1_large.jpg&w=592&aoe=1&q=100","http://link/to/new.jpg");


console.log(newUrl);

UpdatE: Make it into a nice function for you: http://jsfiddle.net/wesbos/KH25r/1/

function swapOutSource(url, newSource) {
    params = url.split('&');
    var src = params[0].split('=');
    params.shift();
    src[1] = newSource;
    var newUrl = ( src.join('=') + params.join('&')); 
    return newUrl; 
}

Then go at it!

var newUrl = swapOutSource("http://localhost/mysite/includes/phpThumb.php?src=http://media2.jupix.co.uk/v3/clients/4/properties/795/IMG_795_1_large.jpg&w=592&aoe=1&q=100","http://link/to/new.jpg");


console.log(newUrl);
风流物 2024-12-07 21:06:51

如果你仔细观察,你会发现关于 URL 的两个令人惊讶的事情:(1) 它们看起来很简单,但细节和极端情况实际上很困难,(2) 令人惊讶的是 JavaScript 没有提供完整的 API 来使使用它们变得更容易。我认为一个成熟的库是为了避免人们自己重新发明轮子或复制一些随机的家伙聪明但可能有错误的正则表达式代码片段。也许尝试 URI.js (http://medialize.github.io/URI.js/

If you look closely you'll see two surprising things about URLs: (1) they seem simple, but the details and corner cases are actually hard, (2) Amazingly JavaScript doesn't provide a full API for making working with them any easier. I think a full-fledged library is in order to avoid people re-inventing the wheel themselves or copying some random dude's clever, but likely buggy regex code snippet. Maybe try URI.js (http://medialize.github.io/URI.js/)

枕头说它不想醒 2024-12-07 21:06:51

我使用这种方法:

  • 替换历史记录中的url
  • 返回已删除参数的值

    function getUrlParameterAndRemoveParameter(paramName) {
        var url = window.location.origin + window.location.pathname;
        var s = window.location.search.substring(1);
        var pArray = (s == "" ? [] : s.split('&'));
    
        var 参数值 = null;
        var pArrayNew = [];
        for (var i = 0; i < pArray.length; i++) {
            var pName = pArray[i].split('=');
            if (pName[0] === 参数名称) {
                paramValue = pName[1] === 未定义? true :decodeURIComponent(pName[1]);
            }
            别的 {
                pArrayNew.push(pArray[i]);
            }
        }
    
        url += (pArrayNew.length == 0 ? "" : "?" + pArrayNew.join('&'));
        window.history.replaceState(window.history.state, document.title, url);
    
        返回参数值;
    }
    

I use this method which:

  • replace the url in the history
  • return the value of the removed parameter

    function getUrlParameterAndRemoveParameter(paramName) {
        var url = window.location.origin + window.location.pathname;
        var s = window.location.search.substring(1);
        var pArray = (s == "" ? [] : s.split('&'));
    
        var paramValue = null;
        var pArrayNew = [];
        for (var i = 0; i < pArray.length; i++) {
            var pName = pArray[i].split('=');
            if (pName[0] === paramName) {
                paramValue = pName[1] === undefined ? true : decodeURIComponent(pName[1]);
            }
            else {
                pArrayNew.push(pArray[i]);
            }
        }
    
        url += (pArrayNew.length == 0 ? "" : "?" + pArrayNew.join('&'));
        window.history.replaceState(window.history.state, document.title, url);
    
        return paramValue;
    }
    
面如桃花 2024-12-07 21:06:51

2020 答案,因为我缺少自动删除参数的功能,所以:

基于我最喜欢的答案 https://stackoverflow.com/a /20420424/6284674
我将其与以下功能结合起来:

  • 如果基于答案 null 或 '',则

    自动删除 URL 参数href="https://stackoverflow.com/a/25214672/6284674">https://stackoverflow.com/a/25214672/6284674

  • 可选地推送直接在window.location中更新的URL bar

  • IE 支持,因为它仅使用正则表达式,没有 URLSearchParams

JSfiddle: https://jsfiddle.net/MickV/zxc3b47u/


function replaceUrlParam(url, paramName, paramValue){
    if(paramValue == null || paramValue == "")
        return url
        .replace(new RegExp('[?&]' + paramValue + '=[^&#]*(#.*)?
), '$1')
        .replace(new RegExp('([?&])' + paramValue + '=[^&]*&'), '$1');   
    url = url.replace(/\?$/,'');
    var pattern = new RegExp('\\b('+paramName+'=).*?(&|$)')
    if(url.search(pattern)>=0){
        return url.replace(pattern,'$1' + paramValue + '$2');
    }
    return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue 
}

// Orginal URL (default jsfiddle console URL)
//https://fiddle.jshell.net/_display/?editor_console=true

console.log(replaceUrlParam(window.location.href,'a','2'));   
//https://fiddle.jshell.net/_display/?editor_console=true&a=2

console.log(replaceUrlParam(window.location.href,'a',''));   
//https://fiddle.jshell.net/_display/?editor_console=true

console.log(replaceUrlParam(window.location.href,'a',3));   
//https://fiddle.jshell.net/_display/?editor_console=true&a=3

console.log(replaceUrlParam(window.location.href,'a', null));   
//https://fiddle.jshell.net/_display/?editor_console=true&

//Optionally also update the replaced URL in the window location bar
//Note: This does not work in JSfiddle, but it does in a normal browser
function pushUrl(url){
    window.history.pushState("", "", replaceUrlParam(window.location.href,'a','2'));   
}


pushUrl(replaceUrlParam(window.location.href,'a','2'));   
//https://fiddle.jshell.net/_display/?editor_console=true&a=2

pushUrl(replaceUrlParam(window.location.href,'a',''));   
//https://fiddle.jshell.net/_display/?editor_console=true

pushUrl(replaceUrlParam(window.location.href,'a',3));   
//https://fiddle.jshell.net/_display/?editor_console=true&a=3

pushUrl(replaceUrlParam(window.location.href,'a', null));   
//https://fiddle.jshell.net/_display/?editor_console=true&

2020 answer since I was missing the functionality to automatically delete a parameter, so:

Based on my favorite answer https://stackoverflow.com/a/20420424/6284674 :
I combined it with the ability to:

  • automatically delete an URL param if the value if null or '' based on answer https://stackoverflow.com/a/25214672/6284674

  • optionally push the updated URL directly in the window.location bar

  • IE support since it's only using regex and no URLSearchParams

JSfiddle: https://jsfiddle.net/MickV/zxc3b47u/


function replaceUrlParam(url, paramName, paramValue){
    if(paramValue == null || paramValue == "")
        return url
        .replace(new RegExp('[?&]' + paramValue + '=[^&#]*(#.*)?
), '$1')
        .replace(new RegExp('([?&])' + paramValue + '=[^&]*&'), '$1');   
    url = url.replace(/\?$/,'');
    var pattern = new RegExp('\\b('+paramName+'=).*?(&|$)')
    if(url.search(pattern)>=0){
        return url.replace(pattern,'$1' + paramValue + '$2');
    }
    return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue 
}

// Orginal URL (default jsfiddle console URL)
//https://fiddle.jshell.net/_display/?editor_console=true

console.log(replaceUrlParam(window.location.href,'a','2'));   
//https://fiddle.jshell.net/_display/?editor_console=true&a=2

console.log(replaceUrlParam(window.location.href,'a',''));   
//https://fiddle.jshell.net/_display/?editor_console=true

console.log(replaceUrlParam(window.location.href,'a',3));   
//https://fiddle.jshell.net/_display/?editor_console=true&a=3

console.log(replaceUrlParam(window.location.href,'a', null));   
//https://fiddle.jshell.net/_display/?editor_console=true&

//Optionally also update the replaced URL in the window location bar
//Note: This does not work in JSfiddle, but it does in a normal browser
function pushUrl(url){
    window.history.pushState("", "", replaceUrlParam(window.location.href,'a','2'));   
}


pushUrl(replaceUrlParam(window.location.href,'a','2'));   
//https://fiddle.jshell.net/_display/?editor_console=true&a=2

pushUrl(replaceUrlParam(window.location.href,'a',''));   
//https://fiddle.jshell.net/_display/?editor_console=true

pushUrl(replaceUrlParam(window.location.href,'a',3));   
//https://fiddle.jshell.net/_display/?editor_console=true&a=3

pushUrl(replaceUrlParam(window.location.href,'a', null));   
//https://fiddle.jshell.net/_display/?editor_console=true&

巴黎盛开的樱花 2024-12-07 21:06:51

除了@stenix之外,这对我来说非常有效

 url =  window.location.href;
    paramName = 'myparam';
        paramValue = $(this).val();
        var pattern = new RegExp('('+paramName+'=).*?(&|$)') 
        var newUrl = url.replace(pattern,'$1' + paramValue + '$2');
        var n=url.indexOf(paramName);
        alert(n)
        if(n == -1){
            newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue 
        }
        window.location.href = newUrl;

这里不需要保存“url”变量,只需替换当前的url

In addition to @stenix, this worked perfectly to me

 url =  window.location.href;
    paramName = 'myparam';
        paramValue = $(this).val();
        var pattern = new RegExp('('+paramName+'=).*?(&|$)') 
        var newUrl = url.replace(pattern,'$1' + paramValue + '$2');
        var n=url.indexOf(paramName);
        alert(n)
        if(n == -1){
            newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue 
        }
        window.location.href = newUrl;

Here no need to save the "url" variable, just replace in current url

小糖芽 2024-12-07 21:06:51

像这样的事情怎么样:

<script>
function changeQueryVariable(keyString, replaceString) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    var replaced = false;
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == keyString) {
            vars[i] = pair[0] + "="+ replaceString;
            replaced = true;
        }
    }
    if (!replaced) vars.push(keyString + "=" + replaceString);
    return vars.join("&");
}
</script>

How about something like this:

<script>
function changeQueryVariable(keyString, replaceString) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    var replaced = false;
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == keyString) {
            vars[i] = pair[0] + "="+ replaceString;
            replaced = true;
        }
    }
    if (!replaced) vars.push(keyString + "=" + replaceString);
    return vars.join("&");
}
</script>
思念满溢 2024-12-07 21:06:51

试试这个

var updateQueryStringParam = function (key, value) {

    var baseUrl = [location.protocol, '//', location.host, location.pathname].join(''),
        urlQueryString = document.location.search,
        newParam = key + '=' + value,
        params = '?' + newParam;

    // If the "search" string exists, then build params from it
    if (urlQueryString) {
        var updateRegex = new RegExp('([\?&])' + key + '[^&]*');
        var removeRegex = new RegExp('([\?&])' + key + '=[^&;]+[&;]?');

        if( typeof value == 'undefined' || value == null || value == '' ) { // Remove param if value is empty
            params = urlQueryString.replace(removeRegex, "$1");
            params = params.replace( /[&;]$/, "" );

        } else if (urlQueryString.match(updateRegex) !== null) { // If param exists already, update it
            params = urlQueryString.replace(updateRegex, "$1" + newParam);

        } else { // Otherwise, add it to end of query string
            params = urlQueryString + '&' + newParam;
        }
    }

    // no parameter was set so we don't need the question mark
    params = params == '?' ? '' : params;

    window.history.replaceState({}, "", baseUrl + params);
};

try this

var updateQueryStringParam = function (key, value) {

    var baseUrl = [location.protocol, '//', location.host, location.pathname].join(''),
        urlQueryString = document.location.search,
        newParam = key + '=' + value,
        params = '?' + newParam;

    // If the "search" string exists, then build params from it
    if (urlQueryString) {
        var updateRegex = new RegExp('([\?&])' + key + '[^&]*');
        var removeRegex = new RegExp('([\?&])' + key + '=[^&;]+[&;]?');

        if( typeof value == 'undefined' || value == null || value == '' ) { // Remove param if value is empty
            params = urlQueryString.replace(removeRegex, "$1");
            params = params.replace( /[&;]$/, "" );

        } else if (urlQueryString.match(updateRegex) !== null) { // If param exists already, update it
            params = urlQueryString.replace(updateRegex, "$1" + newParam);

        } else { // Otherwise, add it to end of query string
            params = urlQueryString + '&' + newParam;
        }
    }

    // no parameter was set so we don't need the question mark
    params = params == '?' ? '' : params;

    window.history.replaceState({}, "", baseUrl + params);
};
烂人 2024-12-07 21:06:51

一种没有正则表达式的解决方案,看起来更容易一些,我一直在寻找

它支持端口、哈希参数等。

使用浏览器属性元素作为解析器。

function setUrlParameters(url, parameters) {
    var parser = document.createElement('a');
    parser.href = url;

    url = "";

    if (parser.protocol) {
        url += parser.protocol + "//";
    }

    if (parser.host) {
        url += parser.host;
    }

    if (parser.pathname) {
        url += parser.pathname;
    }

    var queryParts = {};

    if (parser.search) {
        var search = parser.search.substring(1);

        var searchParts = search.split("&");
        for (var i = 0; i < searchParts.length; i++) {
            var searchPart = searchParts[i];

            var whitespaceIndex = searchPart.indexOf("=");

            if (whitespaceIndex !== -1) {
                var key = searchPart.substring(0, whitespaceIndex);
                var value = searchPart.substring(whitespaceIndex + 1);

                queryParts[key] = value;
            } else {
                queryParts[searchPart] = false;
            }
        }
    }

    var parameterKeys = Object.keys(parameters);

    for (var i = 0; i < parameterKeys.length; i++) {
        var parameterKey = parameterKeys[i];

        queryParts[parameterKey] = parameters[parameterKey];
    }


    var queryPartKeys = Object.keys(queryParts);

    var query = "";

    for (var i = 0; i < queryPartKeys.length; i++) {
        if (query.length === 0) {
            query += "?";
        }
        if (query.length > 1) {
            query += "&";
        }

        var queryPartKey = queryPartKeys[i];

        query += queryPartKey;

        if (queryParts[queryPartKey]) {
            query += "=";

            query += queryParts[queryPartKey];
        }
    }

    url += query;

    if (parser.hash) {
        url += parser.hash;
    }

    return url;
}

A solution without Regex, a little bit easier on the eye, one I was looking for

This supports ports, hash parameters etc.

Uses browsers attribute element as a parser.

function setUrlParameters(url, parameters) {
    var parser = document.createElement('a');
    parser.href = url;

    url = "";

    if (parser.protocol) {
        url += parser.protocol + "//";
    }

    if (parser.host) {
        url += parser.host;
    }

    if (parser.pathname) {
        url += parser.pathname;
    }

    var queryParts = {};

    if (parser.search) {
        var search = parser.search.substring(1);

        var searchParts = search.split("&");
        for (var i = 0; i < searchParts.length; i++) {
            var searchPart = searchParts[i];

            var whitespaceIndex = searchPart.indexOf("=");

            if (whitespaceIndex !== -1) {
                var key = searchPart.substring(0, whitespaceIndex);
                var value = searchPart.substring(whitespaceIndex + 1);

                queryParts[key] = value;
            } else {
                queryParts[searchPart] = false;
            }
        }
    }

    var parameterKeys = Object.keys(parameters);

    for (var i = 0; i < parameterKeys.length; i++) {
        var parameterKey = parameterKeys[i];

        queryParts[parameterKey] = parameters[parameterKey];
    }


    var queryPartKeys = Object.keys(queryParts);

    var query = "";

    for (var i = 0; i < queryPartKeys.length; i++) {
        if (query.length === 0) {
            query += "?";
        }
        if (query.length > 1) {
            query += "&";
        }

        var queryPartKey = queryPartKeys[i];

        query += queryPartKey;

        if (queryParts[queryPartKey]) {
            query += "=";

            query += queryParts[queryPartKey];
        }
    }

    url += query;

    if (parser.hash) {
        url += parser.hash;
    }

    return url;
}
差↓一点笑了 2024-12-07 21:06:51

这是用 paramVal 替换 url param 的函数

function updateURLParameter(url, param, paramVal){
        if(!url.includes('?')){
            return url += '?' + param + '=' + paramVal;
        }else if(!url.includes(param)){
            return url += '&' + param + '=' + paramVal;
        }else {
            let paramStartIndex = url.search(param);
            let paramEndIndex = url.indexOf('&', paramStartIndex);
            if (paramEndIndex == -1){
                paramEndIndex = url.length;
            }
            let brands = url.substring(paramStartIndex, paramEndIndex);
    
            return url.replace(brands, param + '=' + paramVal);
        }
    }

Here is function which replaces url param with paramVal

function updateURLParameter(url, param, paramVal){
        if(!url.includes('?')){
            return url += '?' + param + '=' + paramVal;
        }else if(!url.includes(param)){
            return url += '&' + param + '=' + paramVal;
        }else {
            let paramStartIndex = url.search(param);
            let paramEndIndex = url.indexOf('&', paramStartIndex);
            if (paramEndIndex == -1){
                paramEndIndex = url.length;
            }
            let brands = url.substring(paramStartIndex, paramEndIndex);
    
            return url.replace(brands, param + '=' + paramVal);
        }
    }
悲凉≈ 2024-12-07 21:06:51

一个更长但可能更灵活的答案依赖于两个函数。第一个生成包含所有参数的键/值字典,另一个自行进行替换。这应该适用于旧浏览器,并且还可以在参数不存在时创建该参数。

var get_all_params=function(url)
{               
    var regexS = /(?<=&|\?)([^=]*=[^&#]*)/;
    var regex = new RegExp( regexS,'g' );
    var results = url.match(regex);
    if(results==null)
    {
        return {};
    }
    else
    {
        returned={};
        for(i=0;i<results.length;i++)
        {
            var tmp=results[i];                
            var regexS2="([^=]+)=([^=]+)";
            var regex2 = new RegExp( regexS2 );
            var results2 = regex2.exec(tmp );                
            returned[results2[1]]=results2[2];
        }
        return returned;
    }   
}

var replace_param=function(url, param, value)
{
    var get_params=get_all_params(url);
    var base_url=url.split("?");
    get_params[param]=value;
    var new_params=Array();
    for(key in get_params)
    {
        new_params.push(key+"="+get_params[key]);
    }
    return base_url[0]+"?"+new_params.join("&");
}

调用示例:

var url ="https://geoserver.xxx.com/geoserver/project?service=WFS&version=1.0.0&request=GetFeature&typename=localities";
url=replace_param(url, "service","WMS");

A lengthier, but maybe more flexible, answer that relies on two functions. The first one produces a key/value dictionary with all the parameters, the other one doing the substitution itself. This should work on old browsers, and can also create the parameter when it doesn't exist.

var get_all_params=function(url)
{               
    var regexS = /(?<=&|\?)([^=]*=[^&#]*)/;
    var regex = new RegExp( regexS,'g' );
    var results = url.match(regex);
    if(results==null)
    {
        return {};
    }
    else
    {
        returned={};
        for(i=0;i<results.length;i++)
        {
            var tmp=results[i];                
            var regexS2="([^=]+)=([^=]+)";
            var regex2 = new RegExp( regexS2 );
            var results2 = regex2.exec(tmp );                
            returned[results2[1]]=results2[2];
        }
        return returned;
    }   
}

var replace_param=function(url, param, value)
{
    var get_params=get_all_params(url);
    var base_url=url.split("?");
    get_params[param]=value;
    var new_params=Array();
    for(key in get_params)
    {
        new_params.push(key+"="+get_params[key]);
    }
    return base_url[0]+"?"+new_params.join("&");
}

Exemple of call :

var url ="https://geoserver.xxx.com/geoserver/project?service=WFS&version=1.0.0&request=GetFeature&typename=localities";
url=replace_param(url, "service","WMS");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文