How to capitalize the first letter of a string in JavaScript

Asked 2 years ago, Updated 2 years ago, 42 views

this is a test -> This is a test the Eiffel Tower -> The Eiffel Tower /index.html -> /index.html

I want to capitalize the first letter of the string in JavaScript like this, but I don't know how. How shall I do it?

capitalize javascript string

2022-09-22 22:00

1 Answers

I did it like this.

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

If you write it like this, 'string'.capitalizeFirstLetter() // String You can write it like this.


2022-09-22 22:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.