Capitalize the first character of multi word string

The following sample of code capitalizes the first character of every word in a string.

And you can do the ruby string capitalization in this way (from David Felstead)


These icons link to social bookmarking sites where readers can share and discover new web pages.

  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • ThisNext
  • MisterWong
  • Wists
  • blinkbits
  • BlinkList

7 Comments »

  1. David Felstead said,

    May 5, 2007 @ 5:14 pm

    This will actually modify the string, so if you had (substituting _ for spaces) “hello___how___are___you” would be replaced with “Hello_How_Are_You”, i.e. the spaces are removed.

    This might be a better solution:

    str.gsub(/^[a-z]|\s+[a-z]/) { |a| a.upcase }

  2. admin said,

    May 5, 2007 @ 7:32 pm

    Thanks for the comment David.
    Actually, the string will be modified, it will just out put a new string with upper case words.

    However, I like your solution more, ill add it to the post!

  3. pvh said,

    August 28, 2007 @ 1:36 pm

    Just to clarify David’s post, the error in your original function is that it modifies whitespace. It will replace all whitespace with a single space, including tabs or multiple spaces. Thus the string “Hello world!” will become “Hello World!” using your original function.

  4. pvh said,

    August 28, 2007 @ 1:38 pm

    How appropriate, the blog ate my whitespace! My example should look like: “Hello____________________world” becoming “Hello_world”.

  5. Robert B. said,

    October 11, 2007 @ 8:27 am

    Preseneted solution with regular expression doesn’t take into consideration string with national characters, i.e. not from regular a-z range.

  6. rajat said,

    November 15, 2007 @ 12:52 am

    Very useful,

    thanks

  7. Yavor Ivanov said,

    May 14, 2008 @ 11:34 am

    Hey it’s very simple for national characters as well.
    If you have problems with local chars just always put the string through chars.
    In this case it is simply:

    str.chars.upcase.to_s

    Greetings from Bulgaria!

RSS feed for comments on this post · TrackBack URI

Leave a Comment