santa
santa

Reputation: 12512

get numeric part of ID

If I have the following element:

<div id="ITEM22"></div>

I can get the id like this:

$(this).attr('id');

But how can I get just the numeric part of this if, i.e. 22 ?

EDIT: ITEM is always a prefix.

Upvotes: 6

Views: 4039

Answers (5)

tanyuk
tanyuk

Reputation: 1

This extracts digital part of a string using a Regular Expression.

var numericPart = id.match(/\d+/);

Upvotes: 0

suren
suren

Reputation: 981

<div id="ITEM22"></div>

var id = $(this).attr('id');  
var numeric_part = id.replace(/[A-Z]+/, '');  //Output : 22

Upvotes: 0

slandau
slandau

Reputation: 24052

var whatYouWant = getNo($(this).attr('id'));

function getNo(stringNo)
{
    var parsedNo = "";
    for(var n=0; n<stringNo.length; n++)
    {
        var i = stringNo.substring(n,n+1);
        if(i=="1"||i=="2"||i=="3"||i=="4"||i=="5"||i=="6"||i=="7"||i=="8"||i=="9"||i=="0")
            parsedNo += i;
    }
    return parseInt(parsedNo);
}

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

If you always have the prefix ITEM then you can

var numeric = this.id.replace('ITEM','');

and as @Felix mentions in the comments you can convert it directly to a usable number (instead of just a string representation it) by using the + unary operator MDC docs instead

var numeric = +this.id.replace('ITEM','');

Additionally, i have changed the $(this).attr('id') to this.id since this already refers to the object you want and you can directly access its id attribute with this.id

Upvotes: 6

Alex Wayne
Alex Wayne

Reputation: 187014

var thenumber22 = $(this).attr('id').match(/(\d+)/)[1]

Upvotes: 17

Related Questions