bhfuser
bhfuser

Reputation: 33

Capitalize first letter in java script

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

Upvotes: 3

Views: 1933

Answers (2)

Michael
Michael

Reputation: 3426

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

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

Upvotes: 1

James Allardice
James Allardice

Reputation: 166031

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);

Upvotes: 6

Related Questions