Matching all integers


I’m not the best at regex so I came here for some help!

I’m trying to match all integers before and after the hyphen:


This is what I tried but always returns null

var divID = '12345-5';
var idPattern = /^[0-9]+$/; //Matching one or more numbers before the hyphen
var id2Pattern = /^\\-[0-9]+$/; //Matching starts from the hyphen and all numbers that proceed
var id2 = divID.match(id2Pattern);



var divID = ‘12345-5’;

Or even divId.split(‘-’), if you are sure of the input format

You have another problem too. It’s invalid for an identifier to start with a number.

Other than that, you can use \d instead of [0-9], and by matching /\d+/ you’ll get an array of all groups of numbers. [‘12345’, ‘5’]

var divID = '12345-5';
var matches = divID.match(/\\d+/);
var id2 = matches[1];
alert(id2); // alerts 5


I’ve had a chance to test out pmw57 way and it’s not returning an array.

If I do matches[1] it returns undefined but if I do matches[0] it returns all numbers.

Another thing to note, all numbers before the hyphen will be unique. So it can be 12-4 or 14587-1 etc.


Went with mrhoo way. Worked perfect.


Sorry man, the global setting was missing when it was typed out.

It should be /\d+/g

var divID = '12345-5';
var matches = divID.match(/\\d+/g);
var id2 = matches[1];
alert(id2); // alerts 5