String Operations Lesson

Code Pattern

String operations are actions that inspect or transform text. A program can trim whitespace, convert text to lowercase, check for a word, replace part of a message, or extract a smaller piece of a string.

Code Runner Challenge

String Operations Lesson

View IPYNB Source
%%js

// CODE_RUNNER: String Operations Lesson

let searchText = "  JavaScript Lessons  ";
let normalized = searchText.trim().toLowerCase();
let containsScript = normalized.includes("script");

console.log(normalized);
console.log("Contains script: " + containsScript);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Many string methods return a new value instead of changing the original string. That means the result needs to be stored in a variable or used immediately.

The operations happen in order: remove extra spaces, lowercase the text, then search it. This makes the search more reliable.