Regex using javascript to return just numbers

Asked
Active3 hr before
Viewed126 times

7 Answers

javascriptusing
90%

If I have a string like "something12" or "something102", how would I use a regex in javascript to return just the number parts?,Here is the solution to convert the string to valid plain or decimal numbers using Regex:, Meta Stack Overflow ,Thanks for contributing an answer to Stack Overflow!

Regular expressions:

var numberPattern = /\d+/g;

'something102asdfkj1948948'.match(numberPattern)

To concatenate them:

'something102asdfkj1948948'.match(numberPattern).join('')
load more v
88%

The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. Regular expression for extracting a number is (/(\d+)/).,Extract a number from a string using JavaScript,How to calculate the number of days between two dates in javascript?,Example 2: This example uses match() function to extract number from string.

72%

// https://regex101.com/r/qyq3PG/1
// or 
/^[0-9]*$/
load more v
65%

However, the above method will return the first occurrence of the numbers. Therefore, if you have a string like arun_4874_541, using the above method, will return only 4874.,Must read: How to filter out only numbers in an Array using pure JavaScript,I want to extract the number 4874 from the above string and there are two simple methods to this.,Related: How to add a Dash or Hyphen after every 3rd character using RegEx in JavaScript

<script>
   var tName = 'arun_4874';
   alert(tName.match(/\d+/)); <
   /html>
load more v
75%

This would return an Array with two elements inside, '102' and '1948948'. Operate as you wish. If it doesn't match any it will return null.,This will prevent errors if no matches are found and return an empty string:,IMO the #3 answer at this time by Chen Dachao is the right way to go if you want to capture any kind of number, but the regular expression can be shortened from:,If I have a string like "something12" or "something102", how would I use a regex in javascript to return just the number parts?

Regular expressions:

var numberPattern = /d+/g;

'something102asdfkj1948948'.match(numberPattern)

To concatenate them:

'something102asdfkj1948948'.match(numberPattern).join('')
load more v
40%

Simply use a regular expression in the replace function to get numbers from the string in JS. Regular expression for extracting a number is (/(\d+)/).,The g at the end of the regular expression literal is for “global” meaning that it replaces all matches and not just the first.,Here is HTML example code, Regular expression will serve your purpose:,\D matches a character that is not a numerical digit. So any non-digit is replaced by an empty string. The result is only the digits in a string.

Simply use a regular expression in the replace function to get numbers from the string in JS. Regular expression for extracting a number is (/(\d+)/).

string.replace(/[^0-9]/g, '');
load more v
22%

If there isn't a match, the .match() method will return null.,Regular expressions, abbreviated as regex, or sometimes regexp, are one of those concepts that you probably know is really powerful and useful. But they can be daunting, especially for beginning programmers.,Unlike the .test() method which just returns true or false, .match() will actually return the match against the string you're testing. For example:,If there's a match, the .match() method will return an array with the match. We'll go into more detail about this in a bit.

Unlike the .test() method which just returns true or false, .match() will actually return the match against the string you're testing. For example:

const csLewisQuote = 'We are what we believe we are.';
const regex1 = /are/;
const regex2 = /eat/;

csLewisQuote.match(regex1); // ["are", index: 3, input: "We are what we believe we are.", groups: undefined]

csLewisQuote.match(regex2); // null

The first mode is when the global flag (g) isn't used, like in the example above:

const csLewisQuote = 'We are what we believe we are.';
const regex = /are/;

csLewisQuote.match(regex); // ["are", index: 3, input: "We are what we believe we are.", groups: undefined]

But say you want to see how many times the word "are" occurs in a string. To do that, just add the global search flag to your regular expression:

const csLewisQuote = 'We are what we believe we are.';
const regex = /are/g;

csLewisQuote.match(regex); // ["are", "are"]

An important thing to remember is that regex is case sensitive. For example, say you wanted to see how many times the word "we" occurs in your string:

const csLewisQuote = 'We are what we believe we are.';
const regex = /we/g;

csLewisQuote.match(regex); // ["we", "we"]

First, you could use the .toLowercase() method on the string before testing it with the .match() method:

const csLewisQuote = 'We are what we believe we are.'.toLowerCase();
const regex = /we/g;

csLewisQuote.match(regex); // ["we", "we", "we"]

Or if you want to preserve the original case, you could add the case-insensitive search flag (i) to your regular expression:

const csLewisQuote = 'We are what we believe we are.';
const regex = /we/gi;

csLewisQuote.match(regex); // ["We", "we", "we"]

Unlike the .match() method which returns an array or null, .matchAll() requires the global search flag (g), and returns either an iterator or an empty array:

const csLewisQuote = 'We are what we believe we are.';
const regex1 = /we/gi;
const regex2 = /eat/gi;

[...csLewisQuote.matchAll(regex1)];
// [
//   ["We", index: 0, input: "We are what we believe we are.", groups: undefined],
//   ["we", index: 12, input: "We are what we believe we are.", groups: undefined]
//   ["we", index: 23, input: "We are what we believe we are.", groups: undefined]
// ]

[...csLewisQuote.matchAll(regex2)]; // []
const csLewisRepeat = "We We are are";
const repeatRegex = /(\w+)\s\1/g;

csLewisRepeat.match(repeatRegex); // ["We We", "are are"]
const csLewisRepeat = "We We are are";
const repeatRegex = /(\w+)\s\1/g;

[...repeatStr.matchAll(repeatRegex)];

// [
//   ["We We", "We", index: 0, input: "We We are are", groups: undefined],
//   ["are are", "are", index: 6, input: "We We are are", groups: undefined],
// ]

With .replace(), all you need to do is pass it a string or regular expression you want to match as the first argument, and a string to replace that matched pattern with as the second argument:

const campString = 'paidCodeCamp';
const fCCString1 = campString.replace('paid', 'free');
const fCCString2 = campString.replace(/paid/, 'free');

console.log(campString); // "paidCodeCamp"
console.log(fCCString1); // "freeCodeCamp"
console.log(fCCString2); // "freeCodeCamp"

Similar to the .match() method, .replace() will only replace the first matched pattern it finds unless you use regex with the g flag:

const campString = 'paidCodeCamp is awesome. You should check out paidCodeCamp.';
const fCCString1 = campString.replace('paid', 'free');
const fCCString2 = campString.replace(/paid/g, 'free');

console.log(fCCString1); // "freeCodeCamp is awesome. You should check out paidCodeCamp."
console.log(fCCString2); // "freeCodeCamp is awesome. You should check out freeCodeCamp."

And similar to before, whether you pass a string or a regular expression as the first argument, it's important to remember that the matching pattern is case sensitive:

const campString = 'PaidCodeCamp is awesome. You should check out PaidCodeCamp.';
const fCCString1 = campString.replace('Paid', 'free');
const fCCString2 = campString.replace(/paid/gi, 'free');

console.log(fCCString1); // "freeCodeCamp is awesome. You should check out PaidCodeCamp."
console.log(fCCString2); // "freeCodeCamp is awesome. You should check out freeCodeCamp."

The only real difference between .replace() and .replaceAll() is that you need to use the global search flag if you use a regular expression with .replaceAll():

const campString = 'paidCodeCamp is awesome. You should check out paidCodeCamp.';
const fCCString1 = campString.replaceAll('paid', 'free');
const fCCString2 = campString.replaceAll(/paid/g, 'free');

console.log(fCCString1); // "freeCodeCamp is awesome. You should check out freeCodeCamp."
console.log(fCCString2); // "freeCodeCamp is awesome. You should check out freeCodeCamp."
load more v

Other "javascript-using" queries related to "Regex using javascript to return just numbers"