in Javascript

How To Capitalize The First Letter Of A String In JavaScript

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.

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

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 altogether we get the JavaScript ucfirst() alternative.

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

Upgrade to access all content on Paulund

Members unlock all tutorials and snippets

Access to all downloadable content

Access to code examples before others

Sign Up Now

Already a member? Login here

Subscribe To The Weekly Newsletter

Get weekly updates to your email