在我的text_area/text_field中,我想让用户在一些单词周围添加粗体。它的工作原理是:里面有一个*粗体*字。
我使用过.gsub('**', '<b>').html_safe,它几乎可以工作,但问题是输出不完全正确。
预期输出:这里面有一个粗体的单词。
我得到了什么:这里面有一个粗体字.
html:
<p>This has a <b>bold<b> word inside</b></b></p>如何才能只生成被** <b> </b>包围的单词?
发布于 2016-08-05 14:01:34
您可以捕获匹配并将其传递给以下块
string = "This has a **bold** word inside"
string.gsub(/\*\*(\w+)\*\*/) {"<b>#{$1}</b>"}
#=> "This has a <b>bold</b> word inside"它也适用于随后的比赛。
string = "This has a **bold** word inside **bold**"
#=> "This has a <b>bold</b> word inside <b>bold</b>"编辑
如果您也想捕获空格,那么将\s添加到regex中
string = "This has a ** bold with spaces ** word inside **bold**"
string.gsub(/\*\*([\w\s]+)\*\*/) { "<b>#{$1}</b>" }
#=> "This has a <b> bold with spaces </b> word inside <b>bold</b>"https://stackoverflow.com/questions/38790260
复制相似问题