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.
My trip to Mozilla Summit 2013 was incredible. I've spent so much time focusing on my project that I had lost sight of all of the great work Mozillians were putting out. MozSummit provided the perfect reminder of how brilliant my colleagues are and how much...
I spent a few months experimenting with different approaches for writing simple, elegant and maintainable media queries with Sass. Each solution had something that I really liked, but I couldn't find one that covered everything I needed to do, so I ventured into creating my...
CSS cubes really showcase what CSS has become over the years, evolving from simple color and dimension directives to a language capable of creating deep, creative visuals. Add animation and you've got something really neat. Unfortunately each CSS cube tutorial I've read is a bit...
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