Search code examples
javascriptcapitalize

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


Solution

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