Regular Expressions Basics
Matching Digits
Find the first run of digits in a string.
match-digits
`match` returns details about a pattern match. Reading the first entry gives the text that matched the whole pattern.
Matching Digits
match_digits.js
Replay: real traced execution (multi-file project)
const text = "item42";
const match = text.match(/\d+/);
let digits = "none";
if (match) {
digits = match[0];
}
console.log("text=" + text);
console.log("digits=" + digits);
const text = "box7";
const match = text.match(/\d+/);
let digits = "none";
if (match) {
digits = match[0];
}
console.log("text=" + text);
console.log("digits=" + digits);
const text = "empty";
const match = text.match(/\d+/);
let digits = "none";
if (match) {
digits = match[0];
}
console.log("text=" + text);
console.log("digits=" + digits);
text ← item42, match ← 42, digits ← none
1const text→ item42 = "item42"; //@text="box7", "empty"2const match→ 42 = textitem42.match(/\d+/);3let digits→ none = "none";if (match)
2const match = text.match(/\d+/);3let digits = "none";45if (match42) {6 digits = match[0]42;7}console.log("text=" + text);
6 digits = match[0];7}89console.log("text=" + textitem42);10console.log("digits=" + digits42);outputtext=item42 digits=42
text ← box7, match ← 7, digits ← none
1const text→ box7 = "box7";2const match→ 7 = textbox7.match(/\d+/);3let digits→ none = "none";if (match)
2const match = text.match(/\d+/);3let digits = "none";45if (match7) {6 digits = match[0]7;7}console.log("text=" + text);
6 digits = match[0];7}89console.log("text=" + textbox7);10console.log("digits=" + digits7);outputtext=box7 digits=7
text ← empty, match ← null, digits ← none
1const text→ empty = "empty";2const match→ null = textempty.match(/\d+/);3let digits→ none = "none";45if (match) {6 digits = match[0];7}89console.log("text=" + textempty);10console.log("digits=" + digitsnone);outputtext=empty digits=none