2

I want to capitalize the character of a string whenever it gets space,but not change the other letters. Eg.

the mango tree -> The Mango Tree
an elephant gone -> An Elephant Gone
the xyz hotel -> The Xyz Hotel

in javascript

Nikhil D
  • 2,479
  • 3
  • 21
  • 41
  • Try that http://stackoverflow.com/questions/4878756/javascript-how-to-capitalize-first-letter-of-each-word-like-a-2-word-city – Sena Jun 06 '12 at 13:35
  • @Sena, this answer changes any other capital letters in the string to lowercase. – xcopy Jun 06 '12 at 13:40
  • possible duplicate of [Convert string to title case with javascript](http://stackoverflow.com/questions/196972/convert-string-to-title-case-with-javascript) – CharlesB Jun 06 '12 at 16:38

2 Answers2

2

Since you didn't specify why you need to do this, I'd like to take a guess that it's mostly for text display. If that is the case, you might want to go for a much simpler CSS solution: text-transform:capitalize - let the browser do the work!

Other than that, it seems that this question has been answered before here: Convert string to title case with JavaScript

Community
  • 1
  • 1
Radu
  • 8,561
  • 8
  • 55
  • 91
  • The previous SO answer changes other capital letters in the string to lowercase which the OP did not want. – xcopy Jun 06 '12 at 13:39
2

You could do the following:

var capitalize = function (text)
{
    return text.replace(/\w\S*/g, function (text) { 
        return text[0].toUpperCase() + text.substring(1);
    });
}

alert(capitalize('the dog ran fast'));

Unlike the other suggestions, this would allow you to maintain other capital letters in the string. For example, the string "my variable name is coolCat" would become "My Variable Name Is CoolCat".

xcopy
  • 2,248
  • 18
  • 24