Created
July 18, 2016 20:38
-
-
Save MosheBerman/fb49e060584a9fd6995280fbdcb25ee9 to your computer and use it in GitHub Desktop.
A collection of JavaSscript functions to parse out URLs into distinct data points.
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
// URL Here: | |
var sampleURL = "http://domain.com/#order/food=chicken/drink=coke"; | |
// Function to parse the URL | |
function parseURL(inputURL) { | |
/** | |
Strategy: | |
1. remove the base URL, since we don't need it. | |
2. Grab the rest and split on slashes. | |
3. The first part is the "command" ('#order') | |
4. The rest are key value pairs. | |
*/ | |
// 1. | |
var query = queryFromURL(inputURL); | |
// 2. | |
var action = actionFromQueryString(query); | |
// 3. | |
var parameters = parametersFromQueryString(queryString); | |
/* Do what you'd like. */ | |
console.log("Query: " + query); | |
console.log("Action: " + action); | |
console.log("Parameters: " + parameters); | |
} | |
// Remove the base URL and return a query string | |
function queryFromURL(inputURL) { | |
/** Pull out the matching portion of the string, | |
matching the regular expression. | |
*/ | |
var regex = RegExp(/((http(s)*(:\/\/)){1})([0-z]+)((\.+)([a-z]{2,3}))+(\/)*/g); | |
var output = inputURL.replace(regex, ""); | |
return output; | |
} | |
// Get the action from the query string | |
function actionFromQueryString(queryString) { | |
var components = componentsFromQueryString(queryString); | |
var first = components[0]; | |
return first; | |
} | |
// Get the components from a query string | |
function componentsFromQueryString(queryString) { | |
var components = queryString.split('/'); | |
return components; | |
} | |
// Get the pairs after the action | |
function parametersFromQueryString(queryString) { | |
var components = componentsFromQueryString(queryString); | |
var pairs = components.slice(1, components.length-1); | |
var parameters = {}; | |
// Now convert the pairs into the paramaters | |
// NOTE: Assume proper encoding. | |
// Won't handle missing values or whatever. | |
for (var i = 0; i < pairs.length; i++) { | |
var partsOfPair = pair.split('='); | |
var key = partsOfPair[0]; | |
var value = partsOfPair[1]; | |
parameters[key] = value; | |
} | |
return pairs; | |
} | |
parseURL(sampleURL); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment