Skip to content

Instantly share code, notes, and snippets.

@slaveofcode
Created May 19, 2016 06:59
Show Gist options
  • Save slaveofcode/b20bc08fd4832f93caf1f88fc18b4e43 to your computer and use it in GitHub Desktop.
Save slaveofcode/b20bc08fd4832f93caf1f88fc18b4e43 to your computer and use it in GitHub Desktop.
Javascript Querystring Replacement
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