TypeScript, lesson 8
Most input arrives as text, so string handling is a skill you use in nearly every program.
TypeScript strings are JavaScript strings with the type string, and the editor can list every
method as you type a dot after a string variable.
One rule first: strings are immutable. Methods return a new string and never change the original, so remember to store or print the result.
| Method | Example | Result |
|---|---|---|
toUpperCase() / toLowerCase() | "Hi".toLowerCase() | "hi" |
2 exercises to try what you just read.
trim() | " hi ".trim() | "hi" |
replaceAll(a, b) | "a-b-c".replaceAll("-", "/") | "a/b/c" |
repeat(n) | "ab".repeat(3) | "ababab" |
padStart(n, c) / padEnd(n, c) | "7".padStart(3, "0") | "007" |
Padding only works on strings, so convert numbers first with String(n) or n.toFixed(2).
split gives a string[], array methods transform it, and join puts it back together:
Spreading a string, [..."hello"], gives an array of its characters. Reversing a string is
therefore [...text].reverse().join("").
Patterns like /\s+/ are regular expressions. A few pieces go a long way:
\s whitespace, \d a digit, [a-z] a lower-case letter, [^a-z] anything except one.+ means "one or more of the previous thing".g flag finds every match: "a1b22".match(/\d+/g) gives ["1", "22"].match returns RegExpMatchArray | null: null when nothing matches. TypeScript makes you
handle that case, typically with ?? [] to fall back to an empty array:
?? returns its right side when the left side is null or undefined.
The second exercise is a mini program that uses everything so far: reading input, loops,
decisions, functions, arrays and string formatting. Plan it before you type. Write helper
functions with clear names, such as words(text: string): string[], and keep printing at the
end. Small typed functions are easy to test in your head, and the type checker verifies that
they fit together.
A palindrome reads the same forwards and backwards once you ignore case and everything that is
not a letter or digit: Never odd or even is one. Write a function
isPalindrome(text: string): boolean, then for each input line print yes or no.
Sample input:
Sample output:
Hint: lower-case the text, remove unwanted characters with
replaceAll(/[^a-z0-9]/g, ""), then compare it with its reverse.
Write a small text analyser. Read the whole input (any number of lines; it may be empty). A
word is a run of letters a–z (compare in lower case; everything else separates words).
Print exactly these lines:
L is the number of non-empty lines (lines containing anything other than whitespace).W is the number of words.WORD is the longest word in lower case; if several have the same length, the first one
found. Print - if there are no words.A is the average word length with two decimals, or 0.00 if there are no words.Sample input:
Sample output:
const title = "TypeScript";
title.length; // 10
title[0]; // "T"
title.at(-1); // "t"
title.slice(0, 4); // "Type" (end index is not included)
title.slice(4); // "Script"
title.includes("Script"); // true
title.indexOf("S"); // 4 (-1 if missing)
title.startsWith("Type"); // trueconst slug = " Learn TypeScript Today "
.trim()
.toLowerCase()
.split(/\s+/)
.join("-");
console.log(slug); // learn-typescript-todayconst digits = "no numbers here".match(/\d+/g) ?? [];
console.log(digits.length); // 0Never odd or even
TypeScriptyes
nolines: L
words: W
longest: WORD
average: AThe quick brown fox
jumps over the lazy dog.lines: 2
words: 9
longest: quick
average: 3.89