3

I know this has been answered before, but I'm a newb and I can't get it to work in my situation. Basically, I have pages that call the URL and display part of them on the page. I am hoping to have the first letter of the displayed word capitalize automatically.

This is an example of what i'm using:

<script>
var str = (window.location.pathname);
var str2 = "/seedling/";
document.write(str.substr(str2.length,(str.length - str2.length - 1 ) ) );
</script>

Thanks so much for your help, it is much appreciated!!

James Allardice
  • 156,021
  • 21
  • 318
  • 304
bhfuser
  • 33
  • 3
  • Just for your own knowledge, this is called `Proper Case` – George Johnston Jul 06 '11 at 13:07
  • 1
    possible duplicate of [Capitalize the first letter of string in JavaScript](http://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript) – mplungjan Jul 06 '11 at 13:07
  • Answered [HERE](http://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript). – robamaton Jul 06 '11 at 13:05
  • as this is related to style you may also consider using CSS text-transform capitalize, you have less control over how capitalization is performed and there may be browser issues, but you could easily change to uppercase and lowercase, remove it ... – Christophe Roussy Nov 04 '12 at 14:52

2 Answers2

6

You can capitalise the first letter of a string like this:

var capitalised = yourString.charAt(0).toUpperCase() + yourString.slice(1);

Alternatively:

var capitalised = yourString.charAt(0).toUpperCase() + yourString.substring(1);

Assuming that your document.write call contains the string you want to capitalise:

var yourString = str.substr(str2.length,(str.length - str2.length - 1 ) );
var capitalised = yourString.charAt(0).toUpperCase() + yourString.slice(1);
James Allardice
  • 156,021
  • 21
  • 318
  • 304
  • why slice and not substring(1) – mplungjan Jul 06 '11 at 13:07
  • substring reads better. It is more understandable http://stackoverflow.com/questions/2243824/what-is-the-difference-between-string-slice-and-string-substring-in-javascript – mplungjan Jul 06 '11 at 13:10
  • Perhaps, although it's really a matter of opinion. There are slight differences in the way `slice` and `substring` work, but in this case either will suffice. I've added `substring` as an alternative though. – James Allardice Jul 06 '11 at 13:12
1

If you have LoDash on hand, this can also be achieved using _.capitalize

_.capitalize('FRED');
// => 'Fred'
Michael
  • 3,216
  • 1
  • 17
  • 20