Using rails 4, and having trouble finding documentation on this. I would like to capitalize the first letter of each word in a string but keep already capitalized letters.
I would like the following outputs:
how far is McDonald's from here? => How Far Is McDonald's From Here?
MDMA is also known as molly => MDMA Is Also Known As Molly
i drive a BMW => I Drive A BMW
I thought .titleize
would do it, but that will turn BMW
into Bmw
. Thank you for any help.
In the Change Case dialog box, if you select Proper Case, the first letter of each word will be capitalized, see screenshot: If you choose Sentence case, only the first letter of the text strings are capitalized as following screenshot shown:
If you're working in Microsoft Word. There you can select from upper or lower case, Sentence case with the first letter of each sentence capitalized, Capitalize Each Word for titles, or tOGGLE cASE to swap your writing's current case—perfect for the times you swap capital and lowercase accidentally.
To exclude capital letters from your text, click lowercase. To capitalize all of the letters, click UPPERCASE. To capitalize the first letter of each word and leave the other letters lowercase, click Capitalize Each Word.
In most Mac apps, just select text and right-click on it to see the text options. Hover over the Transformations menu, then select the case you want to capitalize your text. You can make your text upper or lower case—or use the Capitalize option to capitalize the first letter of every word.
You can try the following:
a.split.map{|x| x.slice(0, 1).capitalize + x.slice(1..-1)}.join(' ')
# or
a.split.map{|x| x[0].upcase + x[1..-1]}.join(' ')
#=> ["MDMA Is Also Known As Molly",
"How Far Is McDonald's From Here?",
"I Drive A BMW"]
Demonstration
You can do a custom method like this:
string = "your string IS here"
output = []
string.split(' ').each do |word|
if word =~ /[A-Z]/
output << word
else
output << word.capitalize
end
end
output.join(' ')
Of course, this will not change a word like "tEST" or "tEst" because it has at least one capital letter in it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With