Strings & Regular Expressions
String Basics
const str = "Hello, World!";
str.length; // 13
str[0]; // "H"
str.at(-1); // "!" (ES2022)
str.charAt(0); // "H"
str.charCodeAt(0); // 72 (Unicode code point)
String.fromCharCode(72); // "H"
String Methods (Non-Mutating — strings are immutable)
const s = " Hello World ";
// Case
s.toLowerCase(); // " hello world "
s.toUpperCase(); // " HELLO WORLD "
// Trim
s.trim(); // "Hello World"
s.trimStart(); // "Hello World "
s.trimEnd(); // " Hello World"
// Search
s.includes("World"); // true
s.startsWith("Hello"); // false (has leading spaces)
s.trim().startsWith("Hello"); // true
s.endsWith(" "); // true
s.indexOf("o"); // 5
s.lastIndexOf("o"); // 8
s.search(/world/i); // 8 (regex, returns index)
// Extract
s.slice(2, 7); // "Hello"
s.slice(-6, -2); // "Worl"
s.substring(2, 7); // "Hello" (no negatives)
// Replace
s.replace("World", "JS"); // " Hello JS " (first match)
s.replace(/o/g, "0"); // all matches with regex
s.replaceAll("o", "0"); // ES2021: replace all
// Split
"a,b,c".split(","); // ["a","b","c"]
"hello".split(""); // ["h","e","l","l","o"]
"a b c".split(/\s+/); // ["a","b","c"]
// Pad (ES2017)
"5".padStart(3, "0"); // "005"
"Hi".padEnd(5, "."); // "Hi..."
// Repeat
"ha".repeat(3); // "hahaha"
// Match (regex)
"cat bat hat".match(/[a-z]at/g); // ["cat","bat","hat"]
// matchAll (ES2020) — all matches with capture groups
const text = "cat bat hat";
[...text.matchAll(/([a-z])at/g)].map(m => m[1]); // ["c","b","h"]
Template Literals (Advanced)
// Tagged templates
function sql(strings, ...values) {
return strings.reduce((acc, str, i) =>
acc + str + (values[i] !== undefined
? `'${String(values[i]).replace(/'/g, "''")}'`
: ""), "");
}
const name = "O'Brien";
const query = sql`SELECT * FROM users WHERE name = ${name}`;
// SELECT * FROM users WHERE name = 'O''Brien'
Regular Expressions
// Creating a RegExp
const re1 = /pattern/flags; // literal (preferred)
const re2 = new RegExp("pattern", "flags"); // dynamic (use for variables)
// Flags
// i — case insensitive
// g — global (find all matches, not just first)
// m — multiline (^ and $ match line boundaries)
// s — dotAll (. matches newlines too)
// u — unicode
Regex Patterns Reference
| Pattern | Meaning |
|---|---|
. | Any character except newline |
\d | Digit [0-9] |
\D | Non-digit |
\w | Word char [a-zA-Z0-9_] |
\W | Non-word char |
\s | Whitespace |
\S | Non-whitespace |
^ | Start of string/line |
$ | End of string/line |
* | 0 or more |
+ | 1 or more |
? | 0 or 1 (optional) |
{n} | Exactly n times |
{n,m} | Between n and m times |
[abc] | Any of a, b, c |
[^abc] | None of a, b, c |
(abc) | Capture group |
(?:abc) | Non-capture group |
a|b | a or b |
\b | Word boundary |
Common Regex Patterns
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const phoneRegex = /^\+?[1-9]\d{9,14}$/;
const dateRegex = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
// Named capture groups (ES2018)
const dateMatch = "2024-03-25".match(
/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
);
dateMatch.groups.year; // "2024"
dateMatch.groups.month; // "03"
dateMatch.groups.day; // "25"
// Lookahead / Lookbehind
/\d+(?= dollars)/.test("100 dollars"); // positive lookahead: true
/\d+(?! dollars)/.test("100 euros"); // negative lookahead: true
/(?<=\$)\d+/.test("$100"); // positive lookbehind: true
MCQ — Strings & Regex
Q1: What does "hello".includes("ell") return?
A) 1 (the index)
B) true ✅
C) "ell"
D) false
Answer: B
Q2: What does "a,b,,c".split(",") return?
A) ["a","b","c"]
B) ["a","b","","c"] ✅
C) ["a","b","c",""]
D) Error
Answer: B — The empty string between ,, becomes "" in the array.
Q3: What flag makes a regex case-insensitive?
A) g
B) m
C) i ✅
D) s
Answer: C
Q4: What does "hello".padStart(8, "*") return?
A) "hello***"
B) "***hello" ✅
C) "**hello**"
D) "hello"
Answer: B — padStart pads to the LEFT until total length is 8.
Q5: Are JavaScript strings mutable?
A) Yes B) No — all string methods return NEW strings ✅
Answer: B
Q6: What does \d+ match in regex?
A) A single digit B) One or more digits ✅ C) Zero or more digits D) A decimal number
Answer: B — \d matches one digit, + means one or more.