Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace url parameter with javascript/jquery?

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.

like image 308
Javier Villanueva Avatar asked Aug 24 '11 06:08

Javier Villanueva


People also ask

How can I add or update a query string parameter?

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.


1 Answers

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.
like image 100
stenix Avatar answered Sep 22 '22 10:09

stenix