Last active
February 23, 2017 22:50
-
-
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.
This file contains 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
/* | |
* 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