String methods
- Node.js course
- Beginner
- Lesson 30/116
- 4 min
Learn .length, .toUpperCase and .toLowerCase methods.
String methods
In Node.js text is held in the string type. You find how many characters a string has with the .length property: "Welcome".length evaluates to 7.
String methods are tools that operate on a string. .toUpperCase() upper-cases the letters, .toLowerCase() lower-cases them. For example "book".toUpperCase() returns "BOOK". Methods do not change the original string; they return a new one.
toUpperCase and toLowerCase
To upper-case a string's letters you use .toUpperCase(), to lower-case them .toLowerCase(). Both require an empty parenthesis () because they are method calls.
Important: methods do not modify the original string. const name = "Alex"; name.toUpperCase(); produces a new string "ALEX" but name stays "Alex". To keep the result you assign it to a new variable: const big = name.toUpperCase();.
Practice Upper-case the city
The city variable is set to "Paris". Declare a new variable big and assign the result of city.toUpperCase() to it. Then print big with console.log. The output on a single line must be PARIS.
Starter code
const city = "Paris";
// Declare big with toUpperCase and print itSample solution
const city = "Paris";
const big = city.toUpperCase();
console.log(big);Expected output
PARIS
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is const w = "Welcome"; w.length?
const w = "Welcome";
w.length- 5
- 6
- 7 Correct answer
- 8
Explanation: "Welcome" has 7 characters; length returns 7.
2 Write the toUpperCase call
const name = "Alex";
const big = name____;
const name = "Alex";
const big = name.toUpperCase();
Explanation: .toUpperCase() upper-cases the letters.
3 Match each method to its job
| Term | Meaning |
|---|---|
.length |
Character count |
.toUpperCase() |
Upper-cases letters |
.toLowerCase() |
Lower-cases letters |
"text" |
String literal |