How to replace url parameter with javascript/jquery?
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
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.
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()
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:
- Does not clear a parameter by setting paramValue to null, instead it sets it to empty string. See https://stackoverflow.com/a/25214672 if you want to remove the parameter.