How do I make the first letter of a string uppercase in JavaScript?

javascript, string

Solution

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

Some other answers modify `String.prototype` (this answer used to as well), but I would advise against this now due to maintainability (hard to find out where the function is being added to the `prototype` and could cause conflicts if other code uses the same name/a browser adds a native function with that same name in future).

Problem

How do I make the first character of a string uppercase if it's a letter, but not change the case of any of the other letters? For example: - `"this is a test"` → `"This is a test"` - `"the Eiffel Tower"` → `"The Eiffel Tower"` - `"/index.html"` → `"/index.html"`

Original source

Related problems