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.
While synchronous code is easier to follow and debug, async is generally better for performance and flexibility. Why "hold up the show" when you can trigger numerous requests at once and then handle them when each is ready? Promises are becoming a big part of the JavaScript world...
David asked me if I'd be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you...
One of the website features my customers love to provider their web users is an online dynamic calendar. An online calendar can be used for events, upcoming product specials, memos, and anything else you can think of. I've taken some time to completely...
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