Learn/TypeScript/8. Strings and a small project
Lesson 8 of 15
Sign in

TypeScript, lesson 8

Strings and a small project

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.

Looking inside

Transforming

MethodExampleResult
toUpperCase() / toLowerCase()"Hi".toLowerCase()"hi"

2 exercises to try what you just read.

Exercise 1

Palindrome checker

Press Ctrl Enter or Check to test your code.

Exercise 2

Text statistics

Press Ctrl Enter or Check to test your code.

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).

Splitting, mapping, joining

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("").

Regular expressions, briefly

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".
  • The 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 small project

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.

Further reading

  • MDN: Text formatting
  • MDN: String
  • MDN: Regular expressions
  • MDN: Nullish coalescing operator (??)

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");  // true
const slug = "  Learn TypeScript Today "
  .trim()
  .toLowerCase()
  .split(/\s+/)
  .join("-");
console.log(slug);   // learn-typescript-today
const digits = "no numbers here".match(/\d+/g) ?? [];
console.log(digits.length);   // 0
Never odd or even
TypeScript
yes
no
lines: L
words: W
longest: WORD
average: A
The quick brown fox

jumps over the lazy dog.
lines: 2
words: 9
longest: quick
average: 3.89