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
  • Camera and Video Control with HTML5

    Camera and Video Control with HTML5

    Client-side APIs on mobile and desktop devices are quickly providing the same APIs.  Of course our mobile devices got access to some of these APIs first, but those APIs are slowly making their way to the desktop.  One of those APIs is the getUserMedia API…

  • Creating Scrolling Parallax Effects with CSS

    Creating Scrolling Parallax Effects with CSS

    Introduction For quite a long time now websites with the so called “parallax” effect have been really popular. In case you have not heard of this effect, it basically includes different layers of images that are moving in different directions or with different speed. This leads to a…

  • Animating CSS3 Transforms with MooTools Fx
  • MooTools, mediaboxAdvanced, and Mexico

    MooTools, mediaboxAdvanced, and Mexico

    The lightbox is probably one of my favorite parts of the Web 2.0 revolution. No more having to open new windows (which can bog down your computer quite a bit) to see a larger image, video, etc. Instead, the item loads right into the…


Source link
spot_img

Related articles

Weekly Update 487

I thought Scott would cop it first when he posted about what his solar system really cost him...

Screen-ripping 300 Hz gaming monitor crashes to just $229, touts 1440p resolution and 1ms response time — save $220 on the LG 27-inch UltraGear...

LG is offering a limited-period discount on its UltraGear 27G640A-B 27-inch 1440p gaming monitor. Originally priced at $449.99,...

How to Build Cloud-Based Accounting Software for SMEs

Cloud-based accounting software has become a critical tool for small and medium-sized businesses in the United States. As...

Tech CEOs boast and bicker about AI at Davos

There were times at this week’s meeting of the World Economic Forum when Davos seemed transformed into a...