1

My goal is to turn markdown into text. I am accomplishing this with parsing markdown into HTML using Redcarpet, and then using #strip_tags. My issue is with links, this method only preserves the text of the link and not the link itself.

Ex: I need to preserve the href url after using #strip_tags

# current
<a href="http://www.google.com">google</a> => google
# desired
<a href="http://www.google.com">google</a> => http://www.google.com google

I think the best way would be to use regex, can anyone help implementing this?

My goal is:

def contents_md

# instantiates Redcarpet
    @markdown ||= begin
        options = [autolink: true, fenced_code_blocks: true,     no_intra_emphasis: true, hard_wrap: true, filter_html: true, gh_blockcode: true]
        renderer = Redcarpet::Render::HTML.new(render_options = {})
        Redcarpet::Markdown.new(renderer, *options)
    end

# I need to run contents through a regex before passing to renderer that will turn something like this:
# [text1](https://www.stackoverflow.com) and [text2](https://www.google.com)
# into:
# text1 https://www.stackoverflow.com and text2 https://www.google.com


# then ill pass the result here, which will preserve my links that would be held in <a></a> instead of losing them 
 @markdown.render(contents)
end

# this will then be ran like:
<%= strip_tags(value.contents_md) %>

1 Answer 1

1

You could use gsub with a regexp like this:

text = "[text1](https://www.stackoverflow.com) and [text2](https://www.google.com)"

text.gsub(/\[(.*?)\]\((.*?)\)/, "#{$1} #{$2}")
#=> "text2 https://www.google.com and text2 https://www.google.com"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.