Course progress0%
Course content

Module 1

Module 2

Module 3

Module 4

Module 5

Module 6

Module 7

Module 8

Module 9

Module 10

Module 11

Module 12

Module 13

Module 14

Module 15

Module 16

Module 17

Module 18

25 min

Working with Strings

Apply string operations according to a stated purpose

By the end of this lesson

  • Apply string operations according to a stated purpose
  • Keep source text separate from a search representation

What does matching mean?

A customer searches for " notebook " while the catalog contains "Notebook". Should spaces and capitalization prevent a match? For this exercise, ignore surrounding spaces and case when searching, but preserve the displayed name.

const productName = "Notebook";
const rawSearch = " notebook ";
const search = rawSearch.trim().toLowerCase();
const searchableName = productName.toLowerCase();
console.assert(searchableName.includes(search));
console.assert(productName === "Notebook");
console.assert(productName.startsWith("Note"));
console.assert(productName.toUpperCase() === "NOTEBOOK");

Strings are immutable. These methods return new strings rather than changing the original. length counts UTF-16 code units, which is not always the number of visible characters. For this module's simple text examples the distinction is not observable, but do not use length as a universal user-perceived character count.

includes searches for a substring; startsWith checks the beginning. Both are case-sensitive. trim removes surrounding whitespace, not spaces inside the text.

Split deliberately

const rawTags = "paper, office, school";
const tags = rawTags.split(",").map((tag) => tag.trim());
console.assert(tags.length === 3);
console.assert(tags[1] === "office");

Split turns text into an array based on a separator. This simple format does not support quoted commas like a complete CSV parser would.

Independent exercise

Search for " PEN " in the name "Blue Pen" using the stated case-insensitive policy. Then try an input containing only spaces. Should it match every product?

Correction

After trim and lowercase, pen is included in blue pen. Empty search needs a product decision: includes("") is true for every string. For this exercise reject an empty search before matching. Do not let a language behavior accidentally decide the interface policy.

Review

Separate the original display value from its normalized search value. Cleaning text for one purpose does not justify changing it everywhere.

Lesson complete?

Your progress is saved on this device.