Capitalize the first letter of string using JavaScript

If you come across a scenario where you need to Capitalize the first letter of string using JavaScript then you could easily perform this in one-liner using built-in string methods of JavaScript.

Capitalize the first letter of string using JavaScript

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

If you look at the above code the first method string.charAt(0).toUpperCase() will find the first character from the string and converts it to uppercase.

And later using string.slice() method the new uppercase character is been replaced by the string.

Capitalize the first letter of string using CSS

You could even capitalize the first letter of a string using CSS also, it is simpler and the easy process than writing the JavaScript. Below is the small line of code which applies to the paragraph to capitalize the first letter of the word.

p:first-letter {text-transform:capitalize;}

JavaScript code to capitalize the first letter of each word in a string

If you would like to capitalize the first letter of each word in a string using JavaScript then below function does the job for you.

function capitalizeEveryFirstLetter(str){ 
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like