Explain Codes LogoExplain Codes Logo

How can I extract a number from a string in JavaScript?

javascript
regex
string-manipulation
parseint
Anton ShumikhinbyAnton Shumikhin·Aug 8, 2024
TLDR

To find digits in a string, apply match() with the regex /\d+/ and convert the matches using parseInt():

let num = "Item 123".match(/\d+/); // Find me some digits! let result = num ? parseInt(num[0], 10) : null; // Convert or give me null!

Here, num holds the first series of digits; result returns the numeric conversion or null if no digits are identified.

Come along on a regex journey

All roads leading to numbers

Want to trip across all numbers within a string? Here's how:

let nums = "Item 123, Item 456".match(/\d+/g); // Got'em all! let results = nums ? nums.map(n => parseInt(n, 10)) : []; // Convert'em!

In this scenario, nums becomes an array with your numeric loot, and map() shifts it all into integers.

Keeping the band of numbers together

To retain sequential digits as a whole number:

let numStr = "Winning numbers: 42, 007, 1234".match(/\d+/g).join(''); // Join the gang! let result = parseInt(numStr, 10); // Let's go!

After match() scopes out the digits, join('') lines them up into a digit conga line before parseInt() conversion.

A good scrub for mixed content strings

For those messy strings, you need a cleanup:

let purifiedNum = "Amount: $123.45".replace(/^\D+/g, '').replace(/[^0-9]/g, ''); // Out with the rubbish! let result = parseInt(purifiedNum, 10); // Nice and shiny!

The first replace() says bye-bye to starting non-digits, while the next sweep expels any lingering alphanumerics, leaving "12345" primed for parseInt().

Handling a jungle of string formats

If your strings flaunt varied formats, construct your own path with a regex generator function:

const genRegex = (pattern) => new RegExp(pattern, 'g'); // DIY pathfinder let num = "ID: 00123".match(genRegex("\\d+")); // On the hunt! let result = num ? num.map(n => parseInt(n, 10)) : []; // Gotcha!

Tips from the battlefront

Using parseInt like a pro

Prevent surprise visits from unintended results by setting the radix in parseInt(), especially if the string starts with "0":

let result = parseInt("07", 10); // No trespassing,

Dancing with decimal points

For decimal numbers, use parseFloat() and adjust your regex:

let num = "Price: $123.99".match(/[\d\.]+/); // Performance ready! let result = num ? parseFloat(num[0]) : null; // Showtime!

Tread lightly with non-matches

If digits are off for an outing, match() returns null. Mind your step:

let str = "No digits here!"; // The suspense... let result = str.match(/\d+/); // False alarm? result = result ? parseInt(result[0], 10) : "No digits found"; // Phew!

This trap ensures result won't bite even if no digits are found.

Taming wild patterns

For complex extractions, tame your regex with named capture groups:

let data = "Date: 2023-03-14, Price: $123.45"; // Welcome to the jungle! let regex = /Date: (?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2}), Price: \$(?<price>[\d\.]+)/; // Ready to rumble let match = data.match(regex); // leashing the beast! let priceResult = match.groups.price ? parseFloat(match.groups.price) : null; // Gotcha!

Named capture groups make your regex readable and your code cuddly.