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

text
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);
  1. text ← item42, match ← 42, digits ← none

    1const text→ item42 = "item42"; //@text="box7", "empty"2const match→ 42 = textitem42.match(/\d+/);3let digits→ none = "none";
  2. if (match)

    2const match = text.match(/\d+/);3let digits = "none";45if (match42) {6  digits = match[0]42;7}
  3. console.log("text=" + text);

    6  digits = match[0];7}89console.log("text=" + textitem42);10console.log("digits=" + digits42);
    outputtext=item42
    digits=42
  1. text ← box7, match ← 7, digits ← none

    1const text→ box7 = "box7";2const match→ 7 = textbox7.match(/\d+/);3let digits→ none = "none";
  2. if (match)

    2const match = text.match(/\d+/);3let digits = "none";45if (match7) {6  digits = match[0]7;7}
  3. console.log("text=" + text);

    6  digits = match[0];7}89console.log("text=" + textbox7);10console.log("digits=" + digits7);
    outputtext=box7
    digits=7
  1. 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