Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Capitalize the First Letter of a String in JavaScript

DZone's Guide to

How to Capitalize the First Letter of a String in JavaScript

A small and practical tutorial on building code for this handy little function.

· Web Dev Zone
Free Resource

Make the transition to Node.js if you are a Java, PHP, Rails or .NET developer with these resources to help jumpstart your Node.js knowledge plus pick up some development tips.  Brought to you in partnership with IBM.

Here is a quick code snippet for the JavaScript version of ucfirst. This code snippet will allow you to capitalize the first letter of a string using JavaScript.

function jsUcfirst(string) 
{
    return string.charAt(0).toUpperCase() + string.slice(1);
}

This code snippet will use the JavaScript function charAt to get the character at a certain index.

var firstLetter = string.charAt(0);

Next, we use the uppercase function in JavaScript to set this string to be in capitals.

var uppercaseFirstLetter = string.charAt(0).toUpperCase();

Then we can add the rest of the string on to this capital letter by using the function slice() which will allow us to get the rest of the string and remove the first letter.

var stringWithoutFirstLetter = string.slice(1)

Putting this all together, we get the JavaScript ucfirst() alternative.

function jsUcfirst(string) 
{
    return string.charAt(0).toUpperCase() + string.slice(1);
}

Learn why developers are gravitating towards Node and its ability to retain and leverage the skills of JavaScript developers and the ability to deliver projects faster than other languages can.  Brought to you in partnership with IBM.

Topics:
javascript ,web dev ,string ,snippet

Published at DZone with permission of Paul Underwood, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}