Skip to content

Instantly share code, notes, and snippets.

@atk
Forked from 140bytes/LICENSE.txt
Created July 29, 2011 20:08
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atk/1114620 to your computer and use it in GitHub Desktop.
Save atk/1114620 to your computer and use it in GitHub Desktop.
urlPath

urlPath

A miniature URL path parsing utility. Receives a URL or URL path component string and either a numerical index of the desired part or a keword string for which to search the value within the path:

urlPath('140byt.es/user/atk', 1) // 'atk' urlPath('140byt.es/user/atk', 'user') // still 'atk'

function(
a, // URL path
b // index/key
){
// split path with regexp (multiple slashes, preceding colon optional) and return the following item:
return (a = a.split(/:?\/+/))
// b is number or calculate index of key; if found or number, add 1, otherwise use b (-1 => undefined)
[ +b === b || ~ (b = a.indexOf(b)) ? b + 1 : b ]
}
function(a,b){return(a=a.split(/:?\/+/))[+b===b||~(b=a.indexOf(b))?b+1:b]}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Alex Kloss <alexthkloss@web.de>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "urlPath",
"description": "Parses URL paths for indexed or keyed values",
"keywords": [
"URL",
"path",
"parsing",
"index",
"key"
]
}
<!DOCTYPE html>
<title>urlPath</title>
<div>Expected value: <b>140byt.es rules!</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var urlPath = function(a,b){return(a=a.split(/:?\/+/))[+b===b||~(b=a.indexOf(b))?b+1:b]},
testPath = '140byt.es/another/wish/fulfilled/from/wishlist/obey/our/rules';
document.getElementById( "ret" ).innerHTML = urlPath(testPath, -1)+' '+urlPath(testPath, 'our')+'!';
</script>
@sebastien-p
Copy link

What about (74 bytes) :

function(a,b){return(a=a.split(/:?\/+/))[+b===b||~(b=a.indexOf(b))?b+1:b]}

Or even (86 bytes) :

function(a,b){return(b=location.href.split(/:?\/+/))[+a===a||~(a=b.indexOf(a))?a+1:a]}

?

PS : in your example, "actual value" != "expected value".

@atk
Copy link
Author

atk commented Aug 12, 2011

Thanks, will fix this later.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment