Capitalize the first letter of string in JavaScript

How do I capitalize the first character of a string, 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

solution

If you’re interested in the performance of a few different methods posted:

Here are the fastest methods based on this jsperf test (ordered from fastest to slowest).

As you can see, the first two methods are essentially comparable in terms of performance, whereas altering the String.prototype is by far the slowest in terms of performance.

// 10,889,187 operations/sec
function capitalizeFirstLetter(string) {
  return string[0].toUpperCase() + string.slice(1);
}


// 10,875,535 operations/sec
function capitalizeFirstLetter(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}


// 4,632,536 operations/sec
function capitalizeFirstLetter(string) {
  return string.replace(/^./, string[0].toUpperCase());
}


// 1,977,828 operations/sec
String.prototype.capitalizeFirstLetter = function() {
  return this.charAt(0).toUpperCase() + this.slice(1);
}

enter image description here