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
matchcaptures groups; thegflag finds all.testreturns a boolean.matchAllwith named groups builds a field map.
Keywords and builtins used here
constforof
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.
Step 2 of 3 in Data formats, step 41 of 43 in Language basics.