-
Notifications
You must be signed in to change notification settings - Fork 2
Capitalize First Letter Of String
To capitalize the first letter of a random string, you should follow these steps:
- Get the first letter of the string;
- Convert the first letter to uppercase;
- Get the remainder of the string;
- Concatenate the first letter capitalized with the remainder of the string and return the result;
You should use charAt() method, at index 0, to select the first character of the string.
var string = "freeCodecamp";
string.charAt(0); // Returns "f"NOTE:
charAtis preferable than using[ ](bracket notation) asstr.charAt(0)returns an empty string ('') forstr = ''instead ofundefinedin case of''[0].
You may use toUpperCase() method and convert the calling string to upper case.
var string = "freeCodecamp";
string.charAt(0).toUpperCase(); // Returns "F"You may use slice() method and get the remainder of the string (from the second character, index 1, to the end of the string).
var string = "freeCodecamp";
string.slice(1); // Returns "reeCodecamp"You should create a function that accepts a string as only argument and returns the concatenation of the first letter capitalized string.charAt(0).toUpperCase() and the remainder of the string string.slice(1).
var string = "freeCodecamp";
function capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
capitalizeFirstLetter(string); // Returns "FreeCodecamp"Or you may add that function to the String.prototype for using it directly on a string using the following code (so that the method is not enumerable but can be overwritten or deleted later):
var string = "freeCodecamp";
/* this is how methods are defined in prototype of any built-in Object */
Object.defineProperty(String.prototype, 'capitalizeFirstLetter', {
value: function () {
return this.charAt(0).toUpperCase() + this.slice(1);
},
writable: true, // so that one can overwrite it later
configurable: true // so that it can be deleted later
});
string.capitalizeFirstLetter(); // Returns "FreeCodecamp"stackoverflow - Capitalize the first letter of string in JavaScript
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links