JAVASCRIPT / CHAPTER 03
Strings you can read and change
BeginnerCreate text, inspect it, and keep the result of a simple transformation.
By the end of this chapter
- Create a quoted string
- Read an ASCII string by index
- Store the result of trim and case conversion
The idea
A string is text inside matching quotes. Assign it to a named variable so another statement can use it. In these first examples we use plain ASCII letters: text[0] reads the first letter, and text.length tells us how many letters and spaces there are. Counting starts at zero, so the last position is text.length - 1.
A method is an operation called with a dot and parentheses. trim() returns text with surrounding whitespace removed. toLowerCase() returns a lowercase version. Neither method edits the original string. Save the returned value in another variable, then print both values to see the difference.
Take one step at a time before chaining methods together. First trim the input, then convert the result to lowercase. Once each step makes sense, input.trim().toLowerCase() means the same sequence. Unicode and emoji counting need additional rules; the later text-boundaries chapter handles those after these basics.
const original = " Hello ";
const trimmed = original.trim();
const lower = trimmed.toLowerCase();
console.log("[" + lower + "]");
console.log(trimmed[0], trimmed.length);
console.log("[" + original + "]");[hello] H 5 [ Hello ]
Brackets make edge spaces visible. The transformed value is lowercase without edge spaces, while original still contains both pairs of spaces.
Try it yourself
Store " Coder " in a variable. Produce "[coder]" without changing the original, and print both values.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
Open JavaScript coding challengesCHECK YOUR UNDERSTANDING