ngtonhung
ngtonhung

Reputation: 55

Replace html tags with another tags - ruby on rails

I have a text. For example:

"<p> Lorem ipsum dolor sit amet </p> <video>VIDEO_CODE</video> <p> consectetur adipiscing elit </p>".

Now I need to replace the "video" tag with another one (eg iframe). Then my result should be:

"<p> Lorem ipsum dolor sit amet </p> <iframe type="text/html"  src="https://www.youtube.com/embed/VIDEO_CODE frameborder="0"></iframe> <p> consectetur adipiscing elit </p>"

I am a newbie to Ruby on rails. Someone, can you help me? Can also suggest or give me references link. Thank you very much!

Upvotes: 1

Views: 426

Answers (1)

3limin4t0r
3limin4t0r

Reputation: 21110

If you are using Rails then you should be able to use the Nokogiri gem.

html_string = "<p> Lorem ipsum dolor sit amet </p> <video>VIDEO_CODE</video> <p> consectetur adipiscing elit </p>"

fragment = Nokogiri::HTML.fragment(html_string)
fragment.css('video').each do |video|
  video_code = video.content # add `.strip` for possible whitespace
  iframe = fragment.document.create_element('iframe',
    type: 'text/html',
    src: "https://www.youtube.com/embed/#{video_code}",
    frameborder: 0,
  )
  video.swap(iframe) # or `.replace(iframe)`
end

puts fragment
# <p> Lorem ipsum dolor sit amet </p> <iframe type="text/html" src="https://www.youtube.com/embed/VIDEO_CODE" frameborder="0"></iframe> <p> consectetur adipiscing elit </p>
#=> nil

If you know there is always 1 video element use .at_css('video') instead, which is the same as .css('video').first. To turn the fragment back into a string you can call .to_html or .to_s on it.

You can find most operations you need to know to work with Nokogiri/HTML on the cheat sheet.

Upvotes: 1

Related Questions