Created
May 19, 2016 06:59
-
-
Save slaveofcode/b20bc08fd4832f93caf1f88fc18b4e43 to your computer and use it in GitHub Desktop.
Javascript Querystring Replacement
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 queryStringUrlReplacement(url, param, value) | |
{ | |
var re = new RegExp("[\\?&]" + param + "=([^&#]*)"), match = re.exec(url), delimiter, newString; | |
if (match === null) { | |
// append new param | |
var hasQuestionMark = /\?/.test(url); | |
delimiter = hasQuestionMark ? "&" : "?"; | |
newString = url + delimiter + param + "=" + value; | |
} else { | |
delimiter = match[0].charAt(0); | |
newString = url.replace(re, delimiter + param + "=" + value); | |
} | |
return newString; | |
} | |
This function will add new parameter if not exist before, and will replace the old one if exist, without messing with any of existing querystring parameters. | |
to use `var newUrl = queryStringUrlReplacement('http://www.tomatmerah.com/', 'page', '18');` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment