[javascript] Regex using javascript to return just numbers

If I have a string like "something12" or "something102", how would I use a regex in javascript to return just the number parts?

This question is related to javascript regex

The answer is


I guess you want to get number(s) from the string. In which case, you can use the following:

// Returns an array of numbers located in the string
function get_numbers(input) {
    return input.match(/[0-9]+/g);
}

var first_test = get_numbers('something102');
var second_test = get_numbers('something102or12');
var third_test = get_numbers('no numbers here!');

alert(first_test); // [102]
alert(second_test); // [102,12]
alert(third_test); // null

Here is the solution to convert the string to valid plain or decimal numbers using Regex:

//something123.777.321something to 123.777321
const str = 'something123.777.321something';
let initialValue = str.replace(/[^0-9.]+/, '');
//initialValue = '123.777.321';

//characterCount just count the characters in a given string
if (characterCount(intitialValue, '.') > 1) {
 const splitedValue = intitialValue.split('.');
 //splittedValue = ['123','777','321'];
 intitialValue = splitedValue.shift() + '.' + splitedValue.join('');
 //result i.e. initialValue = '123.777321'
}

As per @Syntle's answer, if you have only non numeric characters you'll get an Uncaught TypeError: Cannot read property 'join' of null.

This will prevent errors if no matches are found and return an empty string:

('something'.match( /\d+/g )||[]).join('')


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:

/[-]{0,1}[\d]*[\.]{0,1}[\d]+/g

to:

/-?\d*\.?\d+/g

For example, this code:

"lin-grad.ient(217deg,rgba(255, 0, 0, -0.8), rgba(-255,0,0,0) 70.71%)".match(/-?\d*\.?\d+/g)

generates this array:

["217","255","0","0","-0.8","-255","0","0","0","70.71"]

I've butchered an MDN linear gradient example so that it fully tests the regexp and doesn't need to scroll here. I think I've included all the possibilities in terms of negative numbers, decimals, unit suffixes like deg and %, inconsistent comma and space usage, and the extra dot/period and hyphen/dash characters within the text "lin-grad.ient". Please let me know if I'm missing something. The only thing I can see that it does not handle is a badly formed decimal number like "0..8".

If you really want an array of numbers, you can convert the entire array in the same line of code:

array = whatever.match(/-?\d*\.?\d+/g).map(Number);

My particular code, which is parsing CSS functions, doesn't need to worry about the non-numeric use of the dot/period character, so the regular expression can be even simpler:

/-?[\d\.]+/g

You could also strip all the non-digit characters (\D or [^0-9]):

_x000D_
_x000D_
let word_With_Numbers = 'abc123c def4567hij89'_x000D_
let word_Without_Numbers = word_With_Numbers.replace(/\D/g, '');_x000D_
_x000D_
console.log(word_Without_Numbers)
_x000D_
_x000D_
_x000D_


If you want only digits:

var value = '675-805-714';
var numberPattern = /\d+/g;
value = value.match( numberPattern ).join([]);
alert(value);
//Show: 675805714

Now you get the digits joined


If you want dot/comma separated numbers also, then:

\d*\.?\d*

or

[0-9]*\.?[0-9]*

You can use https://regex101.com/ to test your regexes.


Using split and regex :

    var str = "fooBar0123".split(/(\d+)/);
    console.log(str[0]); // fooBar
    console.log(str[1]); // 0123

The answers given don't actually match your question, which implied a trailing number. Also, remember that you're getting a string back; if you actually need a number, cast the result:

item=item.replace('^.*\D(\d*)$', '$1');
if (!/^\d+$/.test(item)) throw 'parse error: number not found';
item=Number(item);

If you're dealing with numeric item ids on a web page, your code could also usefully accept an Element, extracting the number from its id (or its first parent with an id); if you've an Event handy, you can likely get the Element from that, too.


var result = input.match(/\d+/g).join([])

Everything that other solutions have, but with a little validation

// value = '675-805-714'
const validateNumberInput = (value) => { 
    let numberPattern = /\d+/g 
    let numbers = value.match(numberPattern)

    if (numbers === null) {
        return 0
    }  

    return parseInt(numbers.join([]))
}
// 675805714

For number with decimal fraction and minus sign, I use this snippet:

_x000D_
_x000D_
const NUMERIC_REGEXP = /[-]{0,1}[\d]*[.]{0,1}[\d]+/g;

const numbers = '2.2px 3.1px 4px -7.6px obj.key'.match(NUMERIC_REGEXP)

console.log(numbers); // ["2.2", "3.1", "4", "-7.6"]
_x000D_
_x000D_
_x000D_

Update: - 7/9/2018

Found a tool which allows you to edit regular expression visually: JavaScript Regular Expression Parser & Visualizer.

Update:

Here's another one with which you can even debugger regexp: Online regex tester and debugger.

Update:

Another one: RegExr.

Update:

Regexper and Regex Pal.