Luca Romagnoli Luca Romagnoli - 1 year ago 40
Ruby Question

Automatically link URLs and images within html string

Hi i have a string like this:

"<p class='video'>http://vimeo/2342343</p><p class='image'></p><p class='text'>try to write</p><p class='video'>http://vimeo/2234923</p>"

i have to transform it in a string like this:

"<p class='video'><a href='http://vimeo/2342343'>http://vimeo/2342343</a></p><p class='image'><img src='' /></p><p class='text'>try to write</p><p class='video'><a href='http://vimeo/2234923'>http://vimeo/2234923</a></p>"

so how i can get every element and transform it?


Answer Source
html = "<p class='video'>http://vimeo/2342343</p>
        <p class='image'></p>
        <p class='text'>try to write</p>
        <p class='video'>http://vimeo/2234923</p>"

linked = html.gsub( %r{http://[^\s<]+} ) do |url|
  if url[/(?:png|jpe?g|gif|svg)$/]
    "<img src='#{url}' />"
    "<a href='#{url}'>#{url}</a>"

puts linked
#=> <p class='video'><a href='http://vimeo/2342343'>http://vimeo/2342343</a></p>
#=> <p class='image'><img src='' /></p>
#=> <p class='text'>try to write</p>
#=> <p class='video'><a href='http://vimeo/2234923'>http://vimeo/2234923</a></p>