Created
June 29, 2015 16:50
-
-
Save dhigginbotham/dbb0294cf774020792c4 to your computer and use it in GitHub Desktop.
sometimes you gotta parse or serialize some url strings...
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
var util = (function(w,d,$,pub) { | |
var state; | |
state = { | |
current: null, | |
previous: [] | |
}; | |
// http schema/protocol | |
pub.getProtocol = function(str) { | |
var re = /https?:\/\//; | |
return str.match(re); | |
}; | |
// strip off trailing slashes | |
pub.stripTrailing = function(str) { | |
if (str[str.length-1] == '/') str = str.substr(0, str.length-1); | |
return str; | |
}; | |
// get querystring params | |
pub.parseParams = function(str) { | |
var params = {}, queries, temp, i, l; | |
var query = str; | |
var queryString = query.substring(query.indexOf('?')+1); | |
queries = queryString.split("&"); | |
for ( i = 0, l = queries.length; i < l; i++ ) { | |
temp = queries[i].split('='); | |
params[temp[0]] = decodeURIComponent(temp[1]); | |
} | |
return params; | |
}; | |
// accepts an array of paths and joins | |
// them back into a str | |
pub.serializePaths = function(arr) { | |
return '/' + arr.join('/'); | |
}; | |
// serializes param obj, only works single | |
// level | |
pub.serializeParams = function(obj) { | |
var param = null; | |
for (var k in obj) { | |
if (!param) param = []; | |
param.push(k + '=' + obj[k]); | |
} | |
return '?' + param.join('&'); | |
}; | |
pub.parseHref = function(str) { | |
// check for existing state objects and | |
// push them into previous array | |
if (typeof state.current == 'object') { | |
state.previous.push(state.current); | |
} | |
var pieces, paramIndex, protocol, url; | |
// base url obj values | |
url = { | |
$base: null, | |
host: null, | |
params: null, | |
path: null, | |
protocol: null | |
}; | |
if (typeof str == 'undefined') return url; | |
// reset/set current obj | |
url.$base = str; | |
// match/strip protocol | |
protocol = pub.getProtocol(str); | |
if (protocol) { | |
url.protocol = protocol[0]; | |
str = str.replace(protocol[0], ''); | |
} | |
// process params | |
paramIndex = str.indexOf('?'); | |
if (paramIndex != -1) { | |
url.params = pub.parseParams(str); | |
str = str.substr(0, paramIndex); | |
} | |
// strip any trailing slashes | |
str = pub.stripTrailing(str); | |
// break pieces into array | |
pieces = str.split('/'); | |
if (pieces.length) { | |
url.host = pieces[0]; | |
if (pieces.length > 1) { | |
url.path = pieces.splice(1, pieces.length-1); | |
} | |
} | |
pub.current = state.current = url; | |
return url; | |
}; | |
return pub; | |
})(window,document,jQuery, util || {}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment