Extract a Number from a String with JavaScript

Date:

Share post:

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.

Request Metrics real user monitoring
Request Metrics real user monitoring
Request Metrics real user monitoring
  • Create Spinning Rays with CSS3: Revisited
  • An Interview with Eric Meyer

    An Interview with Eric Meyer

    Your early CSS books were instrumental in pushing my love for front end technologies. What was it about CSS that you fell in love with and drove you to write about it? At first blush, it was the simplicity of it as compared to the table-and-spacer…

  • Submit Button Enabling

    Submit Button Enabling

    “Enabling” you ask? Yes. We all know how to disable the submit upon form submission and the reasons for doing so, but what about re-enabling the submit button after an allotted amount of time. After all, what if the user presses the “stop”…

  • Creating Spacers with Flexbox

    Creating Spacers with Flexbox

    I was one of the biggest fans of flexbox before it hit but, due to being shuffled around at Mozilla, I never had the chance to use it in any practice project; thus, flexbox still seems like a bit of a mystery to me.  This greatly…


Source link
spot_img

Related articles

Matrix Push C2 Uses Browser Notifications for Fileless, Cross-Platform Phishing Attacks

Bad actors are leveraging browser notifications as a vector for phishing attacks to distribute malicious links by means...

The New Framework Laptop 16 Has An Upgradable GPU!

A Big Change From The FrameWork Laptop 13 Ars Technica got their hands on the all new FrameWork Laptop...

Fragments Nov 19

I’ve been on the road in Europe for the last couple of weeks, and while I was there...

Logitech Promo Code: $25 Off This Holiday Season

A leader in almost everything tech and home-office related for over 40 years, Swiss-founded Logitech offers a vast...