-2

Given the following string/query string:

ajax/hovercard/hovercard.php?id=100000472545907&extragetparams=%7B%22hc_location%22%3A%22stream%22%7D 

What is the best way to extract the id?

adit
  • 32,574
  • 72
  • 229
  • 373

3 Answers3

2

Try this:

yoururl.match(/id=(.*)&/)[1]

Fiddle

PSL
  • 123,204
  • 21
  • 253
  • 243
  • 4
    hehe, you also were downvoted by some morons ) – zerkms Jun 23 '13 at 02:36
  • This just makes so many assumptions. The URL needs to be parsed properly. – Mulan Jun 23 '13 at 02:36
  • @naomik: we are developers, we solve the tasks as they appear. The theoretics may theoretize for years, while we just provide a solutions for the business. – zerkms Jun 23 '13 at 02:37
  • Oh, I'm sorry. I thought SO was about helping educate people more than just giving them some one-off snippet that works in a narrow solution space. – Mulan Jun 23 '13 at 02:39
  • 2
    @naomik: treat it as a way to teach a person about how to ask better question. Well, I see your point, thank you for being such pedantic. Give me a second to check your answer. See you there. http://stackoverflow.com/a/17245542/251311 --- here is the first. Should I continue? – zerkms Jun 23 '13 at 02:39
  • @PSL: **NO**. Please implement the proper lexer for the URI grammatics and parser for it. Only that answer will be acceptable. It's such a shame to provide one liners for 18k rep guy! – zerkms Jun 23 '13 at 02:45
  • 2
    This won't match if the id is the only URL parameter, correct? – Alex W Jun 23 '13 at 02:47
  • If the query string parameter being searched for doesn't end with an `&` I.E. it's the last parameter then this code will break. It's unreliable. I will upvote if it's fixed. – The Muffin Man Apr 07 '15 at 19:44
1
params = location.search.substring(location.search.indexOf('id')).split('&')[0]

  id = params.substr(3)
0

If it is always shipped in this exact order - then

url.match(/\d+/)

otherwise

url.match(/id=(\d+)/)
zerkms
  • 249,484
  • 69
  • 436
  • 539
  • Sorry, but this is just asking for trouble. – Mulan Jun 23 '13 at 02:34
  • 3
    @naomik: I'm following the task description. If it's not complete - it's not my problem. – zerkms Jun 23 '13 at 02:38
  • @naomik: please prove it's not the best? Please keep in mind that your criterias to determine the solution quality may not match mine. – zerkms Jun 23 '13 at 02:41
  • 3
    @naomik: you're making assumptions that such key may appear in the url. I'm used to using APIs that don't change randomly. Stop making assumptions please. If you want to prove my solution won't work - please ask OP to provide the URL my regex won't match – zerkms Jun 23 '13 at 02:51
  • The second line of code is wrong, you are missing a `[1]`. – Alex W Jun 23 '13 at 02:57
  • @Alex W: it's intentionally - that's a homework for the OP. The same for the first one – zerkms Jun 23 '13 at 02:58