JavaScript Uppercase the First Letter of a String

JavaScript offers many ways to capitalize a string to make the first character uppercase. Learn the various ways, and also find out which one you should use, using plain JavaScript.

Following are the ways:

toUpperCase():

This function applies on a string and change the all letters to uppercase.

string.toUpperCase()

Return Value: This function returns the capitalized string.

slice():

This function applies on a string and slice it according to the passed parameter.

string.slice(start, end)

start: This parameter is required. It specifies the position where to begin the slicing. Indexing starts at position 0.
end: This is optional parameter. It specifies the position from where to end the slicing(without including the end). If this parameter is omitted, It selects all characters from start.
Return Value: This function returns the sliced string.

charAt():

This charAt() function returns the character at given position in string.

string.charAt(index)

Return Value: This function returns the character at specified position in string.

replace():

This is an built-in function in JavaScript which is used to replace a slice of a string with another string or a regular expression. Original string will not affected.

str.replace(A, B)

Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string.
Return Value: It returns a new string with replaced items.

Look at the example below and choose for yourself the appropriate solution

The best way to do this is through a combination of two functions. One uppercases the first letter, and the second slices the string and returns it starting from the second character:

var name = 'nandu'
console.log(name.charAt(0).toUpperCase() + name.slice(1));
// => Nandu

Adding the function to the String prototype:

String.prototype.capitalize = function() {
  return this.charAt(0).toUpperCase() + this.slice(1);
}
var name = 'nandu';
console.log(name.capitalize());
// => Nandu

_.capitalize

If you use Lodash library. This function converts the first character of string to upper case and the remaining to lower case.

var name = 'nandu';
console.log(_.capitalize(name));
// => Nandu

Hapi Joi

If you use Node.js and want the result below, then perhaps Hapi Joi is the right choice

Joi.string().capitalize().validate('nandu singh') 
// => Nandu Singh

Html Css

Don’t forget that if you just want to capitalize for presentational purposes on a Web Page, CSS might be a better solution, just add a capitalize class to your HTML paragraph and use:

.capitalize {
  text-transform: capitalize;
}

Happy Coding!

#javascript #nodejs #uppercase

JavaScript Uppercase the First Letter of a String
1 Likes69.60 GEEK