How to capitalize word with JavaScript

Generally it is better not to interfere with the textual content from JavaScript, but if we ever had to capitalize a word, this is a very cool way to do it:

function Capitalize(word)
{
   return word.charAt(0).toUpperCase() + word.slice(1);
}

And this is my code in action:

Code
//We need to Capitalize the word but we can't modify the HTML
var el = document.getElementById('lblTitle');
el.innerHTML = Capitalize(el.innerHTML);
<div id="lblTitle">france</div>
Preview
france

Where would I ever use this function? For instance in places where I can add my own JavaScript (i.e. in external .js file) but I'm unable to modify the HTML itself.

This function can be used together with some sort of ForEach statement to capitalize all words inside a container, for example:

Code
//using jQuery to simplify selection
var words = $('#lblSentence').html().split(" ");
var newSentence = '';
for (w in words)
{
   words[w] = Capitalize(words[w]);
}
$('#lblSentence').html(words.join(" "));
<div id="lblSentence">the quick brown fox jumps over the lazy dog</div>
Preview
the quick brown fox jumps over the lazy dog
Did you like my article? Share it!
Share/Bookmark

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <csharp>, <css>, <html>, <javascript>, <vb>, <vbnet>, <xml>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters (without spaces) shown in the image.
served by y.co.uk