typestar

Regular expressions in JavaScript

Matching, extracting, and replacing with regex literals.

const log = "user=ada ip=10.0.0.7 status=200";

const user = log.match(/user=(\w+)/)[1];
const numbers = log.match(/\d+/g);
const hasIp = /ip=\d+\.\d+\.\d+\.\d+/.test(log);

const pattern = /(?<key>\w+)=(?<value>\S+)/g;
const fields = {};
for (const match of log.matchAll(pattern)) {
  fields[match.groups.key] = match.groups.value;
}

const masked = log.replace(/ip=\S+/, "ip=hidden");

How it works

  1. match captures groups; the g flag finds all.
  2. test returns a boolean.
  3. matchAll with named groups builds a field map.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
384
Tokens
90
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 57 seconds.

Type this snippet

Step 2 of 3 in Data formats, step 41 of 43 in Language basics.

← Previous Next →

Regular expressions in other languages