tags:

views:

46

answers:

3

hey guys, i know top.location.search retruns ?key=anything&blabla=foobar of my current url. I wonder how i can get the search value out of any url?

if I have e.g. $goToURL = 'http://www.anydomain.com/hello/?path=xyz how can i get ?path=xyz out there and save it to a variable?

regards matt

+2  A: 

[edited based on @Nick's comment]

alert('http://www.anydomain.com/hello/?path=xyz'.split('?', 1)[1]);
karim79
+1 - Should be `.split('?', 1)` though, in case there's a `?` later :)
Nick Craver
Nice one, Nick. Can a '?' even legitimately occur more than once? In any case, I won't edit that in, as your comment does the trick :)
karim79
@karim79: Yes, I've seen URLs with several `?`s in the past.
casablanca
It can happen, but any URL with a non-encoded ? after the first ? is malformed. Some browsers (servers? languages?) will ignore anything following the second one. Others just discard the subsequent ?s.
Alex JL
This will also include any #anchor at the end of the URL, it won't just be the query string
Gareth
man, me=dumb! thank you
@mathiregister - Be advised, @Gareth's solution is the better one.
karim79
+2  A: 

The location properties like .search are also available on <a> elements. So, create an <a> element dynamically and set it's href, and you should be able to access those properties.

var a = document.createElement('a')
a.href = "..."
console.log(a.search)
Gareth
+1 - does it exactly like the browser would, ignoring hashes etc.
Anurag