7

Possible Duplicate:
Capitalize the first letter of string in JavaScript

I am making something called "The HTML Quiz". It's made with JavaScript. When the user first enters it, they have to enter their name. Once they click submit, the name they enter is saved into a variable. It doesn't look nice when it says:

Dear nathan,

You are about to take The HTML Quiz. Please.....

I think it looks better like this:

Dear Nathan,

You are about to take The HTML Quiz. Please.....

But if the user enters their name starting with a lowercase letter, it will stay that way. Is there anyway to make that first letter turn into an uppercase letter if it is lowercase with jQuery?

For example, here is a simple name enter script: http://jsfiddle.net/RcLt6/

If you enter your name in all lowercase, of course, it will be all lowercase. How can I make the first character entered always be capitalized no matter what?

Community
  • 1
  • 1
Nathan
  • 11,814
  • 11
  • 50
  • 93

1 Answers1

5

This will do it:

str = str[0].toUpperCase() + str.slice(1);

Live demo: http://jsfiddle.net/qNJVQ/


Btw, put the INPUT inside the LABEL - that way you won't have to use the for attribute to associate the label with the input field:

<label>
    Name: <input type="text">
</label>
Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • Thanks! Do I just replace `str` with `name`? (`name` is the variable that holds the name value) – Nathan Aug 14 '11 at 02:24
  • @Nathan Be aware that `[]` notation on strings doesn't work in IE7 and IE6, so if you care about those browsers you should go with `str.charAt(0)` instead of `str[0]`. – Šime Vidas Aug 14 '11 at 02:32
  • @Šime Thanks, but I don't really care about IE 8 and down lol. My project doesn't support those. Only IE 9, Firefox, Safari, Google Chrome, etc. (basically all of the **good/modern browsers** are supported) Most of the viewers will be using non-IE browsers anyway so it wont really matter. Thanks for your answer! :) – Nathan Aug 14 '11 at 02:50
  • Use standard-compliant syntax. And don't wrap `` inside ` – Lightness Races in Orbit Aug 14 '11 at 02:55
  • @Tomalak But `str[0]` is standard-compliant - it's in ES5. I must admit I'm not able to find it in the ES5 spec `:)`, but [Mozilla states it is in ES5](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String#section_5), and also kangax lists it as an ES5 feature in [his ES5 table](http://kangax.github.com/es5-compat-table/). – Šime Vidas Aug 14 '11 at 03:18
  • @Tomalak Could you elaborate how it's not portable? – Šime Vidas Aug 14 '11 at 03:20
  • @Sime: I vaguely remember it not working in IE something-or-other. – Lightness Races in Orbit Aug 14 '11 at 03:40
  • On checking, both _are_ indeed standard-compliant. – Lightness Races in Orbit Aug 14 '11 at 03:41