String Manipulation

TypeScript string formatting, methods, and regular expressions.

Template Literals

const name = "Ada";
const age = 30;
const msg = `${name} is ${age}`;         // "Ada is 30"
const tagged = `Hello ${name.toUpperCase()}`; // "Hello ADA"

Template literal types

type EventName = `on${"Click" | "Hover"}`;
// "onClick" | "onHover"

Common Methods

const s = "  Hello, World  ";

s.trim();              // "Hello, World"
s.toLowerCase();        // "  hello, world  "
s.toUpperCase();        // "  HELLO, WORLD  "
s.replace("o", "0");   // "  Hell0, World  "
s.replaceAll("o", "0");// "  Hell0, W0rld  "
s.split(", ");         // ["  Hello", "World  "]
s.startsWith("  H");    // true
s.includes("World");    // true
s.slice(2, 7);          // "Hello"

Regex

const re = /\d+/g;

re.exec("abc123");     // ["123", index: 3]
"abc123".match(/\d+/g); // ["123"]
"abc123".replace(/\d+/g, "#"); // "abc#"

Type-safe string parsing

function parseIntSafe(input: string): number | null {
  const n = Number.parseInt(input, 10);
  return Number.isNaN(n) ? null : n;
}

Next: Classes & Modules