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?
Thanks in advance.
The following solution combines other answers and handles some special cases:
?
character\b
ensures another parameter ending with paramName won't be matchedSolution:
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: