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!
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!
Happy coding!
Top comments (2)
Nice ! Though it's working only with slice and not sPlice.
Hi, you are absolutely right! A big typo there ;)