How to Extract Numbers from a String in JavaScript
Table of Contents
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:
JAVASCRIPTconst 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.
JAVASCRIPTconst string = "The numbers are 123 and 456";
const firstNumber = string.match(/\d+/)[0];
console.log(firstNumber);
BASH123
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:
JAVASCRIPTconst 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.
JAVASCRIPTconst 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.
JAVASCRIPTconst 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!
- Getting Started with TypeScript
- Getting Started with Solid
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- How to deploy a Deno app using Docker
- Getting Started with Deno
- Getting User Location using JavaScript's Geolocation API
- Creating a Twitter bot with Node.js
- Setting Up Stylus CSS Preprocessor
- Using Axios to Pull Data from a REST API