Created
May 17, 2017 13:27
-
-
Save codeasashu/3ba11064a95855fd1deb0fd3817ada1c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function replaceUrlParam(url, paramName, paramValue){ | |
| if(paramValue == null) | |
| paramValue = ''; | |
| var finalurl = null; | |
| var pattern = new RegExp('\\b('+paramName+'=).*?(&|$)'); | |
| if(url.search(pattern)>=0){ | |
| if(paramValue == ''){ | |
| finalurl = url.replace(pattern,'$2'); | |
| if(finalurl.substr(finalurl.length - 1) == '?'){ | |
| finalurl = finalurl.substring(0, finalurl.length - 1); | |
| } | |
| }else{ | |
| finalurl = url.replace(pattern,'$1' + paramValue + '$2'); | |
| } | |
| return finalurl; | |
| /* | |
| if(paramValue != '') | |
| return url.replace(pattern,'$1' + paramValue + '$2'); | |
| else | |
| return url.replace(pattern,'$1' + paramValue + '$2'); | |
| */ | |
| } | |
| return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
useage:
//Sample url: http://example.com/abc/?ref=xxx
var laturl = replaceUrlParam(window.location.href,'lat',position.coords.latitude); //url:http://example.com/abc/?ref=xxx&lat=yyy
var lonurl = replaceUrlParam(laturl,'lon',position.coords.longitude); //url:http://example.com/abc/?ref=xxx&lat=yyy&lon=zzz
window.location =lonurl;