ArticleZip > Regex Using Javascript To Return Just Numbers

Regex Using Javascript To Return Just Numbers

Regex in JavaScript allows you to perform powerful pattern-matching operations on strings. It's a versatile tool that can help you extract specific information, such as numbers, from a text. In this article, we'll focus on using Regex in JavaScript to return just numbers from a given string.

To start, let's understand the basic structure of a regular expression in JavaScript. In JavaScript, you can create a regular expression by enclosing the pattern you want to match between two forward slashes (/). For example, to match any digit in a string, you can use the pattern /d+/.

Now let's delve into how you can use Regex to extract only numbers from a string using JavaScript. Here's a simple example:

Js

const inputString = "I have 123 apples and 456 oranges.";
const numbersArray = inputString.match(/d+/g);
console.log(numbersArray);

In this code snippet, we define an 'inputString' that contains a mix of text and numbers. The `match()` method is then used with the `d+` pattern to extract all the numbers from the string and store them in an array. The 'g' flag ensures that all occurrences of numbers are matched.

When you run this code, the output will be an array `[123, 456]`, which contains the numbers extracted from the input string.

If you want to extract numbers with decimal points or negative signs, you can modify the Regex pattern accordingly. For example, to match decimal numbers, use the pattern `/-?d+(.d+)?/`. Here's how you can use it:

Js

const decimalString = "The price is $12.99, but it's on sale for -5.75.";
const decimalNumbers = decimalString.match(/-?d+(.d+)?/g);
console.log(decimalNumbers);

Running this code will give you an array `[$12.99, -5.75]`, which includes both positive and negative decimal numbers from the input string.

It's important to note that the `match()` method returns an array of matched substrings. If no matches are found, it returns `null`. Hence, always check the value returned by `match()` before processing the results.

In summary, using Regex with JavaScript can be a powerful way to extract specific information, such as numbers, from strings. By understanding the basics of Regex patterns and methods like `match()`, you can efficiently work with textual data in your JavaScript projects. Experiment with different Regex patterns to suit your requirements and enhance your coding skills.

×