jQuery: get the numeric part of an ID attribute

Sometimes we need to extract data from HTML attributes. A typical case is when we need to get the numeric part of an ID attribute. To accomplish this task, we have to exclude all the non-numeric characters from the string. Let's see the details.

We have the following markup:

<p id="test1"></p>
<div id="foo-2"></div>​

We're only interested in the two numbers contained within the ID's value. So we can write the following utility function:

var getNumericPart = function(id) {
    var $num = id.replace(/[^\d]+/, '');
    return $num;
}

The regular expression used above gets rid of all non-numeric characters. Here's an example:

var test1 = $('#test1').attr('id');
alert(getNumericPart(test1));

var foo2 = $('#foo-2').attr('id');
alert(getNumericPart(foo2));

You can see the demo below.

Demo

Live demo

Back to top