Created
November 16, 2011 23:30
-
-
Save glortho/1371866 to your computer and use it in GitHub Desktop.
JS: Helper for dealing with url vars/params in a string
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
/* | |
Param Helper (Jed Verity 2011) | |
USAGE | |
Given query = "?foo=bar&oof=rab": | |
query.param('foo') // 'bar' | |
query.param('oof') // 'rab' | |
query.param(1) // { key: 'foo', val: 'bar' } | |
query.param(2) // { key: 'oof', val: 'rab' } | |
query.param() // [{ key: 'foo, val: 'bar'}, { key: 'oof', val: 'rab' }] | |
query.param('foo', 'nobar') // '?foo=nobar2&oof=rab' | |
query.param('new') // null | |
query.param('new', 'arg') // '?foo=bar&oof=rab&new=arg' | |
Works the same if query = '#foo=bar&oof=rab' or query = '&foo=bar&oof=rab' | |
*/ | |
String.prototype.param = function(key, value) { | |
var index = parseInt(key, 10), | |
re = index || !key ? '([^=]*)' : key, | |
restr = '[?#&]' + re + '=([^&]*)', | |
reobj = RegExp(restr, index || !key ? "g" : ''), | |
match = this.match(reobj), | |
result = null, | |
new_val, obj, stage; | |
if ( match && !value ) { | |
if (index || !key) { | |
obj = []; | |
stage = index ? [match[index-1]] : match; | |
for (var i = 0; i < stage.length; i++) { | |
new_val = stage[i].match(restr); | |
obj.push({key: new_val[1], val: new_val[2]}); | |
} | |
result = !key ? obj : obj[0]; | |
} else { | |
result = decodeURIComponent(match[1].replace(/\+/g, ' ')); | |
} | |
} else if ( value ) { | |
new_val = '&' + key + '=' + value; | |
result = match ? this.replace(match[0], new_val) : (this + new_val) ; | |
} | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment