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.
You can use the browser's native URL API to do this in a fairly simple way, where key and value are your parameter name and parameter value respectively. const url = new URL(location. href); url. searchParams.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With