user6589814 user6589814 - 4 months ago 26
jQuery Question

Ruby on Rails. Replace **Bold** with <b>Bold</b> with gsub()

In my

text_area/text_field
I want to give users option to add bold around some words.
It would work like: This has a ** bold ** word inside.

I have used
.gsub('**', '<b>').html_safe
It almost works, but the problem is that the output is not exactly correct.

Expected Output: This has a bold word inside.

What I get: This has a bold word inside.

html:

<p>This has a <b>bold<b> word inside</b></b></p>


How can I make only the words that is surrounded with ** get
<b> </b>

Answer

You can capture the match and pass it to the following block

string = "This has a **bold** word inside"

string.gsub(/\*\*(\w+)\*\*/) {"<b>#{$1}</b>"}

#=> "This has a <b>bold</b> word inside"

And it works for subsequent matches as well

string = "This has a **bold** word inside **bold**"

#=> "This has a <b>bold</b> word inside <b>bold</b>"

EDIT

If you want to capture spaces as well add \s to the 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>"