简体   繁体   中英

Capitalize a string with html in RoR

I'm building a web app with RoR. How do I take this:

<b>this is my text</b>

and capitalize the first word, so it looks like this

<b>This is my text</b>

I have tried using the capitalize method, but it doesn't work on HTML. Is there any way to do this, preferably without have to install any extra gems?

(For what it's worth, the string ONLY ever contains a <b> tag and text.)

Might not be the most elegant solution but should do the job:

yourstring[3,1] = yourstring[3,1].capitalize

If there is only <b> at the beginning. You might want to use regular expressions to find the first character.

The easiest way would actually to be to use the CSS text-transform property . Assuming your string will always be all lowercase:

<b style="text-transform: capitalize;">this is my text</b>

You could do something like this, may need to be extended if you have multiple bold elements in a single string variable.

t = "<b>this is my text</b>"

t.gsub!(/(<b>)(.*)(<\/b>)/, "#{$1}#{($2).capitalize}#{$3}")

Using this method you have a bit more flexibility. If your tags change, or sometimes you don't have tags, you can easily modify the regex to compensate. Its worth mentioning that this would work as well, but is harder to extend.

t =~ /(<b>)(.*)(<\/b>)/
t =  "#{$1}#{($2).capitalize}#{$3}"

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM