Search code examples
ruby-on-railsrubystringcharactercapitalize

Rails: Capitalize characters after certain string


Using: Rails 3.0.3.

I have a string that could be seen as this one:

<p>hello, how are you? oh, that's nice! i am glad you are fine. i am too.<br />i am glad to have met you.</p>

I want each character following any of <p> <br /> ! ? . to be capitalized. Basically make the string above look good.

Is there a standard functionality for that? What should I do?

ps. Tried to bold the characters in question, but it didn't work...


Solution

  • Going off Niklaos answer, I've improved it slightly to take into account the period and keeping spacing intact in the rendered HTML.

    str.gsub(/(\<p\>|\<br \/\>|[?!.])([\s]*)([[:alpha:]]{1})/) {"#{$1}#{$2}#{$3.capitalize}"}
    

    Edit: Added punctuation characters to be in a single character class, captured all in between whitespace to preserve spacing. Much cleaner.