Capitalize Only First Letter Of Each Word In A String And Leave The Rest Of The Letters Alone

Posted by Weston Ganger on September 21, 2015

You would think titleize or capitalize string methods would be able to handle the fact that I only want the first letter touched. Instead they will lowercase the rest of the letters in the words.

puts "AngularJS".titleize #=> "Angular Js"
puts "AngularJS".capitalize #=> "Angularjs"

So those wont work, heres a trick that will. Im not sure it the most efficient way totally possible but I didnt find any articles about how to do this. So heres my version

str = "angularJS"
puts str[0].upcase + str[1..-1] #=> "AngularJS"

str = "i really LOVE angularJS"
puts str.split.map{|x| x[0].upcase + x[1..-1]}.join(" ") #=> "I Really LOVE AngularJS"

# OR a Better answer posted by Pavel Pravosud
puts str.gsub(/\b\w/, &:upcase) #=> "I Really LOVE AngularJS"

Posted in Rails and Tagged with ruby rails strings 

Want me to help develop your next project or application?

Contact Us

Specializing in Ruby-on-Rails, Javascript, Multi-Platform Electron Desktop Apps and Hybrid Cordova Mobile Apps.

Recommended Posts