Lesson 1 · Unit 05
Strings
Cut, clean and glue text, and turn it into numbers
What you practise
- Strings never change in place,
split,join,trim,replace,includes,slice,padStart, turning text into a number and checking that it worked
Try a question from this lesson
Pick one
toUpperCase gives the same text in capital letters. What does this print?
const word = "ada";
word.toUpperCase();
console.log(word);Correct answer
ada
Why
Line 2 does make "ADA", but as a new string, and nothing keeps it. A string never changes in place, so word still holds "ada". To use the result, store it: const loud = word.toUpperCase();.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Strings never change
You have met methods: functions that belong to a value, called with a dot, as in word.toUpperCase().
Every string method leaves the original alone and returns something new: another string, a number, an array. So the result needs a home, usually a new const.
length has no brackets. It is not a method, just a number the string carries.
const word = "ada";
const loud = word.toUpperCase();
console.log(loud); // ADA
console.log(word); // ada
console.log(word.length); // 3Concept
Cut, change, glue
A very common move: split text into an array, work on the pieces, join them back.
split always returns a string[], even when the pieces look like numbers. join always returns one string.
Because each method returns a value, you can call the next method directly on the result. That is called chaining.
const csv = "a,b,c";
const cells: string[] = csv.split(",");
const row = cells.join(" | ");
console.log(row); // a | b | c
// the same, chained
console.log(csv.split(",").join(" | "));Concept
Text into numbers
Number(text) goes the other way: it reads a number out of a string.
When the text is not a number, the result is NaN, short for "not a number". It is a special value of type number that says the conversion failed.
The compiler cannot warn you: the text only exists when the program runs. Check with Number.isNaN(n).
const a = Number("42");
const b = Number("4x");
console.log(a + 1); // 43
console.log(b); // NaN
console.log(Number.isNaN(b)); // true9 more exercises in the app
- 4× type the answer
- 1× fill the blanks
- 2× multiple choice
- 1× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.