JavaScript string methods and regular expressions

Split, pad, replace, and extract parts of text with strings and regular expressions.

JavaScript
console.log("a-b-c".split("-").reverse().join("+"));
console.log("  padded ".trim().padStart(8, "*"));

const text = "The year 2024 and 1999 were notable";
console.log(text.match(/\d{4}/g).join(" "));

const m = "2024-03-15".match(/^(\d{4})-(\d{2})-(\d{2})$/);
console.log(m[1], m[2], m[3]);

console.log("hello world".replace(/o/g, "0"));
console.log("camelCaseString".replace(/([A-Z])/g, "_$1").toLowerCase());
console.log(/^[\w.]+@[\w.]+\.\w+$/.test("ada@example.com"), /^[\w.]+@[\w.]+\.\w+$/.test("not an email"));
Output
c+b+a
**padded
2024 1999
2024 03 15
hell0 w0rld
camel_case_string
true false

Explanation

Strings are immutable sequences of characters, and their methods return new strings. split turns a string into an array, join does the reverse, trim removes surrounding white space, and padStart fills to a given width. The replace method with a string replaces only the first match, while a regular expression with the g flag replaces every match.

A regular expression describes a pattern of text. \d matches a digit, {4} repeats the previous item four times, parentheses capture a group, and ^ and $ anchor the match to the start and end. match returns the groups of the first match, or all matches with the g flag. In a replacement string, $1 stands for the first captured group.

Explore the dry run
Guided walkthroughReady
1console.log("a-b-c".split("-").reverse().join("+"));
2console.log(" padded ".trim().padStart(8, "*"));
3
4const text = "The year 2024 and 1999 were notable";
5console.log(text.match(/\d{4}/g).join(" "));
6
7const m = "2024-03-15".match(/^(\d{4})-(\d{2})-(\d{2})$/);
8console.log(m[1], m[2], m[3]);
9
10console.log("hello world".replace(/o/g, "0"));
11console.log("camelCaseString".replace(/([A-Z])/g, "_$1").toLowerCase());
12console.log(/^[\w.]+@[\w.]+\.\w+$/.test("ada@example.com"), /^[\w.]+@[\w.]+\.\w+$/.test("not an email"));

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Split into [a, b, c], reverse, and join with +.—
c+b+a
trim removes the spaces; padStart adds stars on the left up to width 8.—
c+b+a
**padded
With the g flag, match returns every four-digit number.—
c+b+a
**padded
2024 1999
m[0] is the whole match and m[1] to m[3] are the captured groups.—
c+b+a
**padded
2024 1999
2024 03 15
g replaces every o, not just the first.—
c+b+a
**padded
2024 1999
2024 03 15
hell0 w0rld
Each capital letter is replaced by an underscore plus itself, and then everything is lower-cased.—
c+b+a
**padded
2024 1999
2024 03 15
hell0 w0rld
camel_case_string
test returns a boolean. This pattern is a rough check, not a full email validator.—
c+b+a
**padded
2024 1999
2024 03 15
hell0 w0rld
camel_case_string
true false

Cost and common mistakes

Each operation is linear in the length of the text for these patterns.

  • match returns null when there is no match, so text.match(...).join fails. Check for null first.
  • A regular expression without the g flag replaces only the first match. A plain string pattern also replaces only the first one.
  • Regular expressions with nested repeats can take exponential time on crafted input (ReDoS). Keep patterns simple for untrusted text.

Try it yourself

What does "2024-03-15".split("-").map(Number) return?

Reveal answer and reasoning

[2024, 3, 15]: the strings are converted to numbers, so "03" becomes 3.

Further reading