Skip to content

Instantly share code, notes, and snippets.

View 0x1211's full-sized avatar
๐Ÿ”

0x1211 0x1211

๐Ÿ”
View GitHub Profile
@0x1211
0x1211 / addOrReplaceQueryParameter.js
Created June 9, 2017 06:53
Add or replace a query parameter in Javascript
function addOrReplaceQueryParameter(url, key, value) {
var keyRegExp = new RegExp('([?&])' + key + '=.*?(&|$)', 'i'),
// Checks if there are already some query parameters and set separator
separator = url.indexOf('?') !== -1 ? '&' : '?';
if (url.match(keyRegExp)) {
// $1 and $2 will set separators
return url.replace(keyRegExp, '$1' + key + '=' + value + '$2');
}