[英]Replace markdown links with text and url
我的目標是將Markdown轉換為文本。 我通過使用Redcarpet將markdown解析為HTML,然后使用#strip_tags來完成此操作。 我的問題是鏈接,此方法僅保留鏈接的文本,而不保留鏈接本身。
例如:使用#strip_tags后,我需要保留href網址
# current
<a href="http://www.google.com">google</a> => google
# desired
<a href="http://www.google.com">google</a> => http://www.google.com google
我認為最好的方法是使用正則表達式,有人可以幫助實現嗎?
我的目標是:
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) %>
您可以將gsub
與這樣的正則表達式一起使用:
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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.