DEV Community

Haakon Helmen Rusås
Haakon Helmen Rusås

Posted on • Edited on

Capitalize first letter in Javascript

In Javascript you have a built in data type called strings. This is used to handle a sequence of characters. This post will attempt to explain one small use case where you wish to change the first letter in a word to upper case.

Setup

We have a string that is comprised of two words, the classic hello World!, but someone forgot to capitalize the "h"!

let string = "hello World!";

let capitalizedString = string[0].toUpperCase() + string.slice(1);

// capitalizedString => Hello World!
Enter fullscreen mode Exit fullscreen mode

Okey so in the first line we declare a variable called string and assign the value "hello World!" to it. In the second line we declare a second variable called capitalizedString. The value for that variable is the result of two operations we preform on string.

Description

Javascript ⇒ String.prototype.toUpperCase()

"The toUpperCase() method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable." - MDN

This method is used to convert all the characters from their initial state to upper case.

Javascript ⇒ String.prototype.slice()

"slice() extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string." - MDN

This method is used to return the rest of the word after the first letter. These to are then combined and returned from the operation. We combine these methods because just using .toUpperCase alone returns only the first letter after the operation.

Hopefully this tip can be useful!

MDN Docs

GeeksforGeeks

Happy coding!

Top comments (2)

Collapse
 
alexsonnay profile image
alexsonnay

Nice ! Though it's working only with slice and not sPlice.

Collapse
 
haakonhr profile image
Haakon Helmen Rusås

Hi, you are absolutely right! A big typo there ;)