How to extract a link from a string?

Discussion in 'JavaScript' started by erezbens, Sep 30, 2008.

  1. #1
    Hi
    How are you?
    I have a form that have a text field for a url of an image from Picasa
    The url of the image is hidden in the string generated by Picasa "Embed image"

    <table style="width:auto;"><tr><td><a href="http://picasaweb.google.com/lh/photo/fB_OHdaSC9uFgZM_pFOwVg"><img src="http://lh6.ggpht.com/er.reshef/SHTBw1V2VsI/AAAAAAAACck/W-KnXb7Re5Q/s144/1%20042.jpg" /></a></td></tr><tr><td style="font-family:arial,sans-serif; font-size:11px; text-align:right">From <a href="http://picasaweb.google.com/er.reshef/394633">בתים לשימור 394633</a></td></tr></table>
    Code (markup):
    How do I extract the url in the src="http://*****.jpg" and save only this to the database?
    I guess I need a text field for the Picasa code
    and a form hidden field for for the url extracted from the picasa code
    ???

    With Ruby this can be done like this:
    a='Picasa code'
    a[%r{src="(.*)" /></a>}, 1]

    but I prefer to do this with Javascript

    I use this for a Real Estate web site that you can see here
    www.5354.co.il (Its in Hebrew)
    all pics are from Picasa
    Right now I copy the code from picasa to a text file and copy the image url from there manualy

    Thank you for your help

    Erez
     
    erezbens, Sep 30, 2008 IP
  2. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #2
    <html>
    <body>
    
    <script type="text/javascript">
    var geturl = new RegExp(/src="http:\/\/(.*)\/[a-zA-Z%0-9-_\.]+\.(jpg|gif|png)/);
    var result = geturl.exec('<table style="width:auto;"><tr><td><a href="http://picasaweb.google.com/lh/photo/fB_OHdaSC9uFgZM_pFOwVg"><img src="http://lh6.ggpht.com/er.reshef/SHTBw1V2VsI/AAAAAAAACck/W-KnXb7Re5Q/s144/1%20042.jpg" /></a></td></tr><tr><td style="font-family:arial,sans-serif; font-size:11px; text-align:right">From <a href="http://picasaweb.google.com/er.reshef/394633">???? ?????? 394633</a></td></tr></table>');
    var imageURL = "http://" + result[1] + "." + result[2];
    
    console.log(imageURL); // outputs: http://lh6.ggpht.com/er.reshef/SHTBw1V2VsI/AAAAAAAACck/W-KnXb7Re5Q/s144.jpg
    </script>
    
    </body>
    </html>
    HTML:
    i'd tweak the regexp further but don't have the time. anyway, you get the idea...
     
    dimitar christoff, Oct 1, 2008 IP
  3. erezbens

    erezbens Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks christoff,
    This is what I did,
    It is working great,

    This is a very good resource to: http://www.quirksmode.org/js/formex.html
     
    erezbens, Oct 2, 2008 IP