views:

59

answers:

4

HI!

I use this the following regex with JS to extract this id 6321890784249785097 from that url

http://video.google.com/googleplayer.swf?docId=6321890784249785097

url.replace(/^[^\$]+.(.{19}).*/,"$1");

But I only cut the last 19 chars from the tail. How can I make to more bullet-proof? Maybe with an explanation so that I learn something?

A: 
url.replace(/.*docId=(\d{19}).*/i,"$1");

this cuts 19 digits that follow docId=.

SilentGhost
Thank you very much. This worked out of the box.
MarcDK
A: 
video[.]google[.]com/googleplayer[.]swf[?]docId=(\d+)

The ID will be captured in reference #1. If you just want to match 19 digits you can chance it to this:

video[.]google[.]com/googleplayer[.]swf[?]docId=(\d{19})
Alix Axel
Thank you very much for your answer!
MarcDK
+1  A: 

This should work a bit better:

/^.*docId=(\d+)$/

This matches all characters up to the 'docId=', then gives you all digits after that up to the end of the url.

Aaron
Thank you very much.
MarcDK
I found this one which works eben better: new RegExp(/.*docid=([\d-]+)(.*?)/i)But thank you!
MarcDK
A: 

Here is the function I use in our app to read url parameters. So far it didn't let me down ;)

urlParam:function(name, w){
    w = w || window;
    var rx = new RegExp('[\&|\?]'+name+'=([^\&\#]+)'),
        val = w.location.href.match(rx);
    return !val ? '':val[1];
}

For the explanation of the regexp:

  • [\&|\?] take either the start of the query string '?' or the separation between parameters '&'
  • 'name' will be the name of the parameter 'docId' in your case
  • ([^\&#]+) take any characters that are not & and #.
    The hash key is often used in one page apps.
    And the parenthesis keep the reference of the content.
  • val will be an array or null/undefined and val[1] the value you are looking for
Mic