CodeBlanks Logo Icon CodeBlanks

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.

Practice 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")).

Starter code

index.js
const helpers = {};
module.exports = helpers;
console.log("Ready");

// Add the capitalize method
// write here

// Call capitalize and print the result
// write here

Sample solution

index.js
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"));

Expected output

Hazır
Merhaba

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Uppercase the first letter

Question
return text[0].____() + text.slice(1);
Answer
return text[0].toUpperCase() + text.slice(1);

Explanation: toUpperCase uppercases a single character.

2 Match each piece to its role

Term Meaning
capitalize Uppercases first letter
toUpperCase Uppercases a character
text.slice(1) Takes the rest of the string
!text Empty string check

3 What does helpers.capitalize("hello") return?

index.js
helpers.capitalize("merhaba")
  • "mERHABA"
  • "MERHABA"
  • "merhaba"
  • "Merhaba" Correct answer

Explanation: Only the first letter is uppercased: Hello.

All lessons in Intermediate