ruby on rails - Bold items in a string based on 1 or more matches -


i have following:

str = "hello world. today wednesday" matchedterms 

matchedterms contains data so:

> "world" > "word, is" 

what update str so:

"hello <b>world</b>. today <b>is</b> wednesday" 

what right way in ruby/rails update string given matchedterms?

thanks

the string#gsub method takes block can make pretty easy (and should more efficient writing iterator/loop).

here's how i'd go this:

matched_terms = ["world", "is"] pattern = regexp.new(matched_terms.join("|"), regexp::ignorecase)  str = "hello world. today wednesday" result = str.gsub(pattern) { |match| "<b>#{match}</b>" } # => "hello <b>world</b>. today <b>is</b> wednesday" 

i couldn't understand why had "word, is" 1 of matchedterms given example output... simplified "is". if wanted "word, is" considered 2 additional terms match on -- "word" , "is" -- i'd clean ahead of time, this:

matched_terms.map! { |mt| mt.split(", ") }.flatten! 

Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -