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!!

4
  • Answered HERE. Commented Jul 6, 2011 at 13:05
  • Just for your own knowledge, this is called Proper Case Commented Jul 6, 2011 at 13:07
  • 1
    possible duplicate of Capitalize the first letter of string in JavaScript Commented Jul 6, 2011 at 13:07
  • 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 ... Commented Nov 4, 2012 at 14:52

2 Answers 2

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); 
Sign up to request clarification or add additional context in comments.

3 Comments

why slice and not substring(1)
substring reads better. It is more understandable stackoverflow.com/questions/2243824/…
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.
1

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

_.capitalize('FRED'); // => 'Fred' 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.