[Solved-5 Solutions] First letter of a string uppercase - javascript tutorial


How to make the first letter of a string as uppercase, but don't change other letters in uppercase ?

Solution 1:

  • In the given strings to make the first string as capitalized: uppercase its first letter, and remaining strings to be lowercase.
  • This problem to overcome by the combination of two functions. The first letter to be uppercases and starting from the second slices string to at the end string as lowercase.
const name = 'wikitechy'
const nameCapitalized = name.charAt(0).toUpperCase() + name.slice(1)

Solution 2:

You can use this solution:

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

Solution 3:

This approach is an object-oriented:

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

And then:

"hello world".capitalize();  =>  "Hello world" 

Solution 4:


p:first-letter {

Solution 5:

In early version that gets the first letter by treating the string as an array:

function capitalize(s)
    return s[0].toUpperCase() + s.slice(1);

This doesn't work in IE 7 or below.

We want remove empty string from the given strings:

function capitalize(s)
    return s && s[0].toUpperCase() + s.slice(1);

Solution 6:

We need to capitalize the first letter and lowercase couldn't be change. Using this function some changes will be occur.

function capitalize(string) {
    return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
capitalize("alfredo")  // => "Alfredo"
capitalize("Alejandro")// => "Alejandro
capitalize("ALBERTO")  // => "Alberto"
capitalize("ArMaNdO")  // => "Armando"

// es6 using destructuring 
const capitalize = ([first,...rest]) => first.toUpperCase() + rest.join('').toLowerCase();

Related Searches to javascript tutorial - First letter of a string uppercase