Extract a Number from a String with JavaScript
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.
![How to Create a RetroPie on Raspberry Pi – Graphical Guide]()
Today we get to play amazing games on our super powered game consoles, PCs, VR headsets, and even mobile devices. While I enjoy playing new games these days, I do long for the retro gaming systems I had when I was a kid: the original Nintendo...
![Responsive Images: The Ultimate Guide]()
Chances are that any Web designers using our Ghostlab browser testing app, which allows seamless testing across all devices simultaneously, will have worked with responsive design in some shape or form. And as today's websites and devices become ever more varied, a plethora of responsive images...
![Create Digg URLs Using PHP]()
Digg recently came out with a sweet new feature that allows users to create Tiny Digg URLs which show a Digg banner at the top allowing easy access to vote for the article from the page. While I love visiting Digg every once in a...
![RealTime Stock Quotes with MooTools Request.Stocks and YQL]()
It goes without saying but MooTools' inheritance pattern allows for creation of small, simple classes that possess immense power. One example of that power is a class that inherits from Request, Request.JSON, and Request.JSONP: Request.Stocks. Created by Enrique Erne, this great MooTools class acts as...
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