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
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
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
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".