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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7171099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:09:55  来源:igfitidea点击:

How to replace url parameter with javascript/jquery?

javascriptjqueryurlurl-parameters

提问by Javier Villanueva

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 srcparameter with another value using javascript or jquery, is this possible?

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

Thanks in advance.

提前致谢。

采纳答案by ZenMaster

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=).*?(&)/,'' + newSrc + '');

EDIT:

编辑:

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

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

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

$1表示内的第一部分()(即,)src=$2表示内的所述第二部分()(即)&,所以这表示你要改变之间的值src&。更清楚一点,应该是这样的:

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.

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

回答by stenix

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
  • \bensures another parameter ending with paramName won't be matched
  • 原始url中不存在该参数
  • 参数是唯一的参数
  • 参数是第一个还是最后一个
  • 新的参数值与旧的相同
  • url 以?字符结尾
  • \b确保另一个以 paramName 结尾的参数不会匹配

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,'' + paramValue + '');
    }
    url = url.replace(/[?#]$/,'');
    return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
}

Known limitations:

已知限制:

回答by Oleg

Nowdays that's possible with native JS

现在使用原生 JS 是可能的

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

回答by user2752173

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

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

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

回答by meliniak

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:

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

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

In this case searchquery param value is changed.

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

Code:

代码:

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

回答by Kinley Christian

If you are having very narrow and specificuse-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

回答by Mayank Dudakiya

I have get best solution to replace the URL parameter.

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

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

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

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

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,'' + paramValue + '');
    }

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

Output

输出

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

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

回答by Laurent

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;
    }
    
  • 替换历史记录中的 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 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;
    }
    

回答by Алексей Бируля

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

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

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.

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

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

然后可以使用 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);

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

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

回答by Ryan

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/)

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