How to Extract Numbers from a String in JavaScript

Updated onbyAlan Morel
How to Extract Numbers from a String in JavaScript

Sometimes you will be faced with a string that contains numbers that you would like to work with.

When this happens, you'll need to extract the numbers from the string, then potentially convert them to a number type before you can work with them.

In this post, we'll learn how to extract a single number and multiple numbers from a string in JavaScript.

How to Extract a Single Number from a String in JavaScript

Before we begin, let's first define the example string we'll be using for this:

JAVASCRIPT
const string = "The numbers are 123 and 456";

Now let's say you would like the first number, 123 from the string.

You can do this by using the match method on the string and passing in a regular expression \d+ that matches the first number in the string.

JAVASCRIPT
const string = "The numbers are 123 and 456"; const firstNumber = string.match(/\d+/)[0]; console.log(firstNumber);
BASH
123

The regular expression \d+ matches one or more digits in the string, so it will match the first number in the string.

How to Extract Multiple Numbers from a String in JavaScript

Now let's see how we can extract multiple numbers from a string.

We can reuse the same string as before:

JAVASCRIPT
const string = "The numbers are 123 and 456";

However, now let's add the g flag which makes this regular expression global, meaning it will match all numbers in the string.

JAVASCRIPT
const string = "The numbers are 123 and 456"; const numbers = string.match(/\d+/g); console.log(numbers);

Now you should get an array of all the numbers in the string:

BASH
[ '123', '456' ]

If you want to convert these into numbers, you can use the map method on the array and convert each number to a number type.

JAVASCRIPT
const string = "The numbers are 123 and 456"; const numbers = string.match(/\d+/g).map(Number); console.log(numbers);
BASH
[ 123, 456 ]

Now you have an array of numbers that you can perform whatever operations you need on.

Conclusion

In this post, we learned how to extract a single number and multiple numbers from a string in JavaScript.

Simply use the match method on the string and pass in a regular expression that matches the numbers you want to extract.

If you want to extract multiple numbers, you can use the g flag to make the regular expression global, which will match all numbers in the string.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.