0

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

matt
  • 42,713
  • 103
  • 264
  • 397
  • I don't think you mean to have that $ there. Technically it's legal but this isn't PHP and the dollar isn't a variable identifier – Gareth Jul 19 '10 at 00:04

2 Answers2

2

[edited based on @Nick's comment]

alert('http://www.anydomain.com/hello/?path=xyz'.split('?', 1)[1]);
karim79
  • 339,989
  • 67
  • 413
  • 406
  • 3
    +1 - Should be `.split('?', 1)` though, in case there's a `?` later :) – Nick Craver Jul 19 '10 at 00:07
  • 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 Jul 19 '10 at 00:08
  • @karim79: Yes, I've seen URLs with several `?`s in the past. – casablanca Jul 19 '10 at 00:14
  • 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. – JAL Jul 19 '10 at 00:18
  • This will also include any #anchor at the end of the URL, it won't just be the query string – Gareth Jul 19 '10 at 00:19
  • 1
    @mathiregister - Be advised, @Gareth's solution is the better one. – karim79 Jul 19 '10 at 00:20
2

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
  • 133,157
  • 36
  • 148
  • 157