01 / 22
"Aa"

String Manipulation
& Regex

Master JavaScript's built-in string methods: split, join, trim, replace, and unlock the power of regular expressions for pattern matching.

JavaScript

Strings: Your Building Blocks of Text

A string is a sequence of characters wrapped in quotes. In JavaScript, strings are immutable: every method returns a new string rather than changing the original.

const greeting = "Hello, World!"; const length = greeting.length; // 13 const char = greeting[0]; // "H"

Why String Methods Matter

Almost every real-world program works with text: parsing user input, formatting output, cleaning data, or searching for patterns. JavaScript gives you a rich toolkit of string methods to handle all of this.

Clean
Remove whitespace and unwanted characters with trim
Transform
Swap text patterns with replace and replaceAll
Restructure
Break apart and reassemble with split and join

The Core Four: split, join, trim, replace

" hello, world " .trim() "hello, world" .split(',') ["hello", " world"] .join('-') "hello- world" .replace('world','devs') "hello, devs"

.split(): String to Array

split(separator) divides a string at each occurrence of the separator and returns an array of substrings.

const csv = "apple,banana,cherry"; const fruits = csv.split(","); // ["apple", "banana", "cherry"] const letters = "hello".split(""); // ["h", "e", "l", "l", "o"] const words = "one two three".split(" ", 2); // ["one", "two"] ← limit parameter

.join(): Array to String

join(glue) is the inverse of split: it combines array elements into a single string, inserting the glue between each element.

const parts = ["2024", "01", "15"]; parts.join("-"); // "2024-01-15" parts.join("/"); // "2024/01/15" parts.join(""); // "20240115"

.trim() & .replace()

// trim() removes leading/trailing whitespace " hello ".trim(); // "hello" " hello ".trimStart(); // "hello " " hello ".trimEnd(); // " hello" // replace() swaps first match "foo bar foo".replace("foo", "baz"); // "baz bar foo" ← only first! // replaceAll() swaps every match "foo bar foo".replaceAll("foo", "baz"); // "baz bar baz"

split vs replace: When to Use Which

split + join replace / replaceAll
Returns Array, then String String directly
Best for Restructuring (change delimiter) Swapping content in place
All occurrences? Always (by nature) Only with replaceAll or /g flag
Example use CSV to TSV Censor a word

Enter Regular Expressions

A regular expression (regex) is a pattern used to match character combinations in strings. In JavaScript, regex is written between forward slashes.

const pattern = /hello/; // literal const pattern2 = new RegExp("hello"); // constructor // Test if a pattern exists in a string /hello/.test("hello world"); // true /xyz/.test("hello world"); // false

Regex Building Blocks

\(\texttt{\d}\)
Any digit (0-9)
\(\texttt{\w}\)
Word character (letter, digit, underscore)
\(\texttt{\s}\)
Whitespace (space, tab, newline)
\(\texttt{.}\)
Any single character (except newline)
\(\texttt{+}\)
One or more of the preceding token
\(\texttt{*}\)
Zero or more of the preceding token
\(\texttt{?}\)
Zero or one (makes it optional)
\(\texttt{[]}\)
Character class: match any one inside

Regex Flags

Flags go after the closing slash and change how the regex engine searches.

\(\texttt{g}\)
Global: find all matches, not just the first one
\(\texttt{i}\)
Case-insensitive: \(\texttt{/hello/i}\) matches "Hello", "HELLO", etc.
\(\texttt{m}\)
Multiline: \(\texttt{\^}\) and \(\texttt{\$}\) match line starts/ends, not just string start/end
"Foo foo FOO".match(/foo/gi); // ["Foo", "foo", "FOO"] ← g + i together

How to Apply These Tools

1
Identify the task: Are you cleaning, searching, splitting, or replacing?
2
Choose your method: Use trim for whitespace, split/join for restructuring, replace for swapping
3
Need a pattern? If a simple string separator is not enough, reach for a regex
4
Pick your flags: Add \(\texttt{g}\) for all matches, \(\texttt{i}\) for case-insensitive
5
Chain if needed: methods return new values, so you can chain: .trim().split(" ").join("-")

Example 1: Clean & Reformat a Name

Task: convert " jane DOE " into "Jane Doe".

const raw = " jane DOE "; // Step 1: Trim whitespace const trimmed = raw.trim(); // "jane DOE" // Step 2: Lowercase everything const lower = trimmed.toLowerCase(); // "jane doe" // Step 3: Split, capitalize each, rejoin const result = lower .split(" ") .map(w => w[0].toUpperCase() + w.slice(1)) .join(" "); // "Jane Doe"

Example 2: Regex Replace for Masking

Task: replace every digit in a credit card number with "*".

const card = "4532-1234-5678-9012"; // \d matches any digit, g flag matches ALL const masked = card.replace(/\d/g, "*"); // "****-****-****-****" // Show only last 4 digits using .slice() const partial = "****-****-****-" + card.slice(-4); // "****-****-****-9012"

Example 3: Validate an Email Pattern

Task: check if a string looks like a valid email address.

const emailRegex = /^\w+@\w+\.\w+$/; emailRegex.test("user@site.com"); // true emailRegex.test("bad@@email"); // false emailRegex.test("no-at-sign.com"); // false
\(\texttt{\^}\)
start
\(\texttt{\w+}\)
username
\(\texttt{@}\)
literal
\(\texttt{\w+}\)
domain
\(\texttt{\backslash.}\)
dot
\(\texttt{\w+}\)
TLD
\(\texttt{\$}\)
end
\(\texttt{\^}\) and \(\texttt{\$}\) anchor the pattern to the full string

Common Mistakes

Forgetting the g flag
Using .replace("a","b") and expecting all "a"s to change. Without \(\texttt{g}\), only the first match is replaced.
Mutating the original
Assuming str.trim() changes str. It does not: you must assign the result: str = str.trim().
Escaping the dot
In regex, \(\texttt{.}\) means "any character." To match a literal dot, escape it: \(\texttt{\backslash.}\)

Method Summary Table

Method Input Output Key Use
.split(sep) String Array Break apart
.join(glue) Array String Reassemble
.trim() String String Clean whitespace
.replace() String String Swap first match
.replaceAll() String String Swap all matches
/regex/.test() String Boolean Pattern check
.match(regex) String Array/null Extract matches

Question 1 of 5

What does "a,b,c".split(",") return?

Question 2 of 5

What does " hello ".trim() return?

Question 3 of 5

What does "foo bar foo".replace("foo", "x") return?

Question 4 of 5

Which regex matches one or more digits?

Question 5 of 5

What does ["red","green","blue"].join(" - ") return?