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

September Patch Tuesday handles 81 CVEs – Sophos News

.Microsoft on Tuesday announced 81 patches affecting 15 product families. Nine of the addressed issues are considered by...

Follow This Advice Before Switching to a New iPhone 17

Are you considering getting one of the new iPhone 17 models? While it’s always tempting to unbox a...

Just Look How Bloody Gross Universal’s ‘Terrifier’ Haunted House Is

Damien Leone, the writer and director of the Terrifier film...

Turtle Beach Unveils New Range Of Officially Licensed Switch 2 Accessories – Controllers, Cases And More

If you're still on the hunt for certain Switch 2 accessories and are looking for alternatives to Nintendo's...