Skip to content

Instantly share code, notes, and snippets.

@kevinweber
Last active February 23, 2017 22:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinweber/58a1b1bdcbab109018dc01a619f9b730 to your computer and use it in GitHub Desktop.
Save kevinweber/58a1b1bdcbab109018dc01a619f9b730 to your computer and use it in GitHub Desktop.
URL query algorithm. A very basic solution to add or replace a property and its value to a URL.
/*
* A very basic solution to add or replace a property and its value to a URL
*
* Usage example:
* url = replaceOrAddValue(url, "property_name", "value");
*
* Source: https://gist.github.com/kevinweber/58a1b1bdcbab109018dc01a619f9b730
*/
function replaceOrAddValue(query, variable, value) {
var findVariable = variable + "=",
variableIndex = query.indexOf(findVariable),
hashIndex = query.indexOf('#'),
hash = '',
splitQuery,
queryFirstPart,
queryLastPart;
// Extract hash
if (hashIndex > -1) {
splitQuery = query.split('#', 2);
query = splitQuery[0];
hash = '#' + splitQuery[1];
}
// Check if value exists already. "-1" means it doesn't exist yet.
if (variableIndex === -1) {
query += query.indexOf('?') === -1 ? '?' : '&';
query += findVariable + value;
} else {
// Split query
queryFirstPart = query.substring(0, variableIndex);
queryLastPart = query.substring(variableIndex);
// Replace value of property
queryLastPart = queryLastPart.replace(/=[\w-]+/, '=' + value);
// Stick two parts back together
query = queryFirstPart + queryLastPart;
}
// Add back the hash if there has been one
query += hash;
return query;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment