.Maui Blog

Extract only numbers from a string in JavaScript

There are many ways to extract numbers from a string in JavaScript.
Here’s the function we use:

function ExtractOnlyNumbersFromString(txt) {
    var numbers = txt.match(/\d/g);
    return (numbers) ? numbers.join("") : "";
}

ExtractOnlyNumbersFromString("a 1 b 2 c 3"); // "123"
ExtractOnlyNumbersFromString("10.2"); // "102"
ExtractOnlyNumbersFromString(".Maui"); // ""
Exit mobile version