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

Incredible Demos

  • By
    Create Twitter-Style Dropdowns Using MooTools

    Twitter does some great stuff with JavaScript. What I really appreciate about what they do is that there aren't any epic JS functionalities -- they're all simple touches. One of those simple touches is the "Login" dropdown on their homepage. I've taken...

  • By
    Chris Coyier’s Favorite CodePen Demos IV

    Did you know you can triple-heart things on CodePen? We’ve had that little not-so-hidden feature forever. You can click that little heart button on any Pen (or Project, Collection, or Post) on CodePen to show the creator a little love, but you can click it again...

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!