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>
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>"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.