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

时间:2021-11-05 08:28:36

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:

我一直在寻找一种有效的方法来实现这一点,但是我一直没能找到它,基本上我需要的是给定这个url,例如:

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?

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

Thanks in advance.

提前谢谢。

9 个解决方案

#1


40  

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

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

$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:

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

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

#2


99  

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

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

  • The parameter does not exist in the original url
  • 该参数在原始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
  • url以a结尾?字符
  • \b ensures another parameter ending with paramName won't be matched
  • \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,'$1' + paramValue + '$2');
    }
    url = url.replace(/\?$/,'');
    return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
}

Known limitations:

已知的限制:

  • Does not clear a parameter by setting paramValue to null, instead it sets it to empty string. See https://*.com/a/25214672 if you want to remove the parameter.
  • 不通过将paramValue设置为null来清除参数,而是将它设置为空字符串。如果要删除参数,请参见https://*.com/a/25214672。

#3


8  

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

#4


3  

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 param值被更改。

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
}

#5


1  

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

更新:将它变成一个很好的函数: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);

#6


1  

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来使使用它们变得更容易。我认为一个成熟的图书馆是为了避免人们重新发明*或复制一些随机的家伙的聪明的,但可能是错误的regex代码片段。也许试着URI。js(http://medialize.github.io/URI.js/)

#7


0  

In addition to @stenix, this worked perfectly to me

除了@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;

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

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

#8


0  

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>

#9


0  

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

#1


40  

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

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

$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:

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

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

#2


99  

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

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

  • The parameter does not exist in the original url
  • 该参数在原始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
  • url以a结尾?字符
  • \b ensures another parameter ending with paramName won't be matched
  • \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,'$1' + paramValue + '$2');
    }
    url = url.replace(/\?$/,'');
    return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
}

Known limitations:

已知的限制:

  • Does not clear a parameter by setting paramValue to null, instead it sets it to empty string. See https://*.com/a/25214672 if you want to remove the parameter.
  • 不通过将paramValue设置为null来清除参数,而是将它设置为空字符串。如果要删除参数,请参见https://*.com/a/25214672。

#3


8  

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

#4


3  

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 param值被更改。

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
}

#5


1  

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

更新:将它变成一个很好的函数: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);

#6


1  

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来使使用它们变得更容易。我认为一个成熟的图书馆是为了避免人们重新发明*或复制一些随机的家伙的聪明的,但可能是错误的regex代码片段。也许试着URI。js(http://medialize.github.io/URI.js/)

#7


0  

In addition to @stenix, this worked perfectly to me

除了@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;

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

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

#8


0  

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>

#9


0  

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