I can get id as follows: $(this).attr('i...">

Get the numerical part of the identifier

If I have the following element:

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

I can get id as follows:

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

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

EDIT: ITEM is always a prefix.

+6
source share
5 answers

If you always have the ITEM prefix, 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 representing the string) using the + unary MDC docs operator instead

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

In addition, I changed $(this).attr('id') to this.id , since this already refers to the desired object, and you can directly access its id attribute using this.id

+6
source
 var thenumber22 = $(this).attr('id').match(/(\d+)/)[1] 
+17
source
 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); } 
0
source
 <div id="ITEM22"></div> var id = $(this).attr('id'); var numeric_part = id.replace(/[AZ]+/, ''); //Output : 22 
0
source

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

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

0
source

Source: https://habr.com/ru/post/887643/


All Articles