CodeBlanks Logo Icon CodeBlanks

replace and split with regex

JavaScript course · Intermediate · Lesson 122/134

Learn to do string operations with regex using replace and split.

replace with a regex

.replace() swaps the first match in a string for new text. Pair it with a regex and you gain the full power of patterns. The g flag replaces every match.

"2024-01-15".replace(/-/g, ".");
// "2024.01.15"

This turns chores like "change every dash into a dot" into one line. You can also reuse the matched parts with $1, $2 references.

split with a regex

.split() breaks a string into pieces. Pass a regex as the separator and you can split on several delimiters at once.

"apple, banana; cherry".split(/[\s,]+/);
// ["apple", "banana", "cherry"]

Here [\s,]+ means one or more spaces or commas. This turns messy text with mixed delimiters into a clean array in one pattern.

Exercise Turn spaces into dashes

Assign the result of text.replace() to cleanedText, turning every run of whitespace into a single dash. Use \s+ for the whitespace pattern and the global flag. Log the result with console.log.

Show example solution
replace takes a regex and a string. Use \s+ for a run of whitespace and the g flag for all.
Example solution:
let cleanedText = text.replace(/\s+/g, "-");
console.log(cleanedText);

Test yourself

  1. What does the g flag do inside .replace()?

    • replaces only the first match
    • replaces nothing
    • replaces every match
    • replaces only the last match
    Show answer

    replaces every match — Correct! The g flag replaces every match.

  2. Call the replace method

    const text = "2024-01-15";
    const nice = text.____(/-/g, ".");
    console.log(nice);
    Show answer
    const text = "2024-01-15";
    const nice = text.replace(/-/g, ".");
    console.log(nice);
  3. Match methods with their behavior

    replace(re, s)
    replace
    split(re)
    split
    /g flag
    replace all
    $1, $2
    group reference

All lessons in Intermediate