How to uppercase the first letter of a string in JavaScript? there are many ways to capitalize a string to make the first character uppercase, let's see how to do it using plain Javascript

One of the most common operations with strings is to make the string capitalized, that is to say, uppercase it’s first letter, and leave the rest of the string as-is.

How to capitalize a string?

The best way to do this is through a combination of two functions. The first one uppercases the first letter with the charAt and the toUpperCase , and the second slice the string and returns it starting from the second character:

const text = 'toncho';
const textCapitalized = `${text.charAt(0).toUpperCase()}${text.slice(1)}`;

console.log(textCapitalized);
// expected output: Toncho

The charAt method returns a new string consisting of the single character or UTF-16 code unit located at a specified offset into the string.

const text = 'toncho';

console.log(text.charAt(0));
// expected output: t

The toUpperCase method will return the string value converted to uppercase

const text = 'toncho';

console.log(text.toUpperCase());
// expected output: TONCHO

The slice method extracts a section of the string and returns its as a new string. This function expects a first parameter called beginIndex that is a zero-based index at which to begin the extraction, and a second optional parameter called endIndex that is a zero-based index before which to end extraction

If the beginIndex is negativa it is treated as str.length + beginIndex, in the other hand if the endIndex is omitted, undefined or greater than str.length extracts to the end of the string and if the endIndex is negativa it is treated as str.length + endIndex.

Note: The slice() method from the String doesn’t modify the original string

const text = 'toncho';

console.log(text.slice(1));
// expected output: oncho

console.log(text.slice(1, 3));
// expected output: on

You can extract this logic to a helper function, which could also checks if the passed parameter is a string, and returns an empty string if not, and also instead of using the charAt method you could use string index

const capitalize = (s) => {
    if (typeof s != 'string') {
        return '';
    }

    return `${s[0].toUpperCase()}${s.slice(1)}`;
}

console.log(capitalize('toncho'));
// expected output: Toncho

console.log(capitalize('t'));
// expected output: T

console.log(capitalize(0));
// expected output: ''

console.log(capitalize([]));
// expected output: ''

Note: String index is not supported in older IE versions


Don’t forget that if you just want to capitalize for presentational purposes on a Web Page, CSS might be the best solution, just use the text-transform property with capitalize

p.capitalize {
    text-transform: capitalize;
}