Node.js
String helpers
Add and test string processing functions.
String helpers
In this lesson we add the first helper method to the helpers object: capitalize. This method uppercases the first letter of a string. In JavaScript toUpperCase() uppercases a letter.
Example: helpers.capitalize = function(text) { if (!text) return text; return text[0].toUpperCase() + text.slice(1); }. Here !text checks for an empty string; text[0] accesses the first character; text.slice(1) takes the rest. Call: helpers.capitalize("hello") returns Hello. We take the previous lesson's skeleton and add this method; since module.exports is a reference, the added method is also exported.
Calling the method
You call a helper method as helpers.methodName(argument). You can print the returned value with console.log.
To see output on separate lines, you write each call in its own console.log. After the previous lesson's "Ready" output, Hello appears on a new line. This way the output of two lessons accumulates. helpers.capitalize is a property added to the helpers object; you access it with a dot. Since module.exports passes a reference, the same method is visible after require in another file.
Exercise Add the capitalize method and call it
Take the previous lesson's helpers skeleton. Add the helpers.capitalize method with body if (!text) return text; return text[0].toUpperCase() + text.slice(1);. Print the result with console.log(helpers.capitalize("hello")).
Show example solution
const helpers = {};
module.exports = helpers;
console.log("Ready");
helpers.capitalize = function(text) {
if (!text) return text;
return text[0].toUpperCase() + text.slice(1);
};
console.log(helpers.capitalize("hello"));
Test yourself
-
Uppercase the first letter
return text[0].____() + text.slice(1);
Show answer
return text[0].toUpperCase() + text.slice(1);
-
Match each piece to its role
- capitalize
- Uppercases first letter
- toUpperCase
- Uppercases a character
- text.slice(1)
- Takes the rest of the string
- !text
- Empty string check
-
What does helpers.capitalize("hello") return?
helpers.capitalize("merhaba")
- "mERHABA"
- "MERHABA"
- "merhaba"
- "Merhaba"
Show answer
"Merhaba" — Only the first letter is uppercased: Hello.
Next lesson: Number helpers