Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capitalize First Letter of all Words and Keep Already Capitalized

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.

like image 832
Kathan Avatar asked Jul 23 '15 00:07

Kathan


People also ask

How to capitalize the first letter of each word in word?

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:

How do I change the Order of capitalization in a sentence?

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.

How do I exclude capital letters from my text?

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.

How do you capitalize letters on a MacBook?

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.


2 Answers

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

like image 96
potashin Avatar answered Oct 13 '22 01:10

potashin


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.

like image 40
Ryan K Avatar answered Oct 12 '22 23:10

Ryan K