Extract a Number from a String with JavaScript

By  on  

User input from HTML form fields is generally provided to JavaScript as a string. We've lived with that fact for decades but sometimes developers need to extract numbers from that string. There are multiple ways to get those numbers but let's rely on regular expressions to extract those numbers!

To employ a regular expression to get a number within a string, we can use \d+:

const string = "x12345david";
const [match] = string.match(/(\d+)/);
match; // 12345

Regular expressions are capable of really powerful operations within JavaScript; this practice is one of the easier operations. Converting the number using a Number() wrapper will give you the number as a Number type.

Recent Features

  • By
    Create Namespaced Classes with MooTools

    MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does.  Many developers create their classes as globals which is generally frowned up.  I mostly disagree with that stance, but each to their own.  In any event...

  • By
    Welcome to My New Office

    My first professional web development was at a small print shop where I sat in a windowless cubical all day. I suffered that boxed in environment for almost five years before I was able to find a remote job where I worked from home. The first...

Incredible Demos

  • By
    Basic AJAX Requests Using MooTools 1.2

    AJAX has become a huge part of the modern web and that wont change in the foreseeable future. MooTools has made AJAX so simple that a rookie developer can get their dynamic pages working in no time. Step 1: The XHTML Here we define two links...

  • By
    Introducing MooTools ElementSpy

    One part of MooTools I love is the ease of implementing events within classes. Just add Events to your Implements array and you can fire events anywhere you want -- these events are extremely helpful. ScrollSpy and many other popular MooTools plugins would...

Discussion

  1. Dekel

    the code string.match(/(\d+)/); assumes that a match is found. If no number is present in the string, string.match(/(\d+)/) will return null, and attempting to destructure null will result in an error

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!