Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery / Get numbers from a string

Tags:

jquery

I have a button on my page with a class of comment_like and an ID like comment_like_123456 but the numbers at the end are variable; could be 1 to 1000000.

When this button is clicked, I need to grab the end number so I can run tasks on other elements with the same suffix.

Is there an easy way of grabbing this number in jQuery?

$('.comment_like').click(function() {     var element_id = $(this).attr('id');      // grab number from element ID      // do stuff with that number  }); 
like image 421
TheCarver Avatar asked Feb 14 '12 19:02

TheCarver


People also ask

How to extract number from string in jQuery?

var str = '3jquery33By333Example3333';

How to get integer value from string in jQuery?

Find code to convert String to Integer using jQuery. To convert, use JavaScript parseInt() function which parses a string and returns an integer. var sVal = '234'; var iNum = parseInt(sVal); //Output will be 234.

Is Numeric in jQuery?

The isNumeric() method in jQuery is used to determine whether the passed argument is a numeric value or not. The isNumeric() method returns a Boolean value. If the given argument is a numeric value, the method returns true; otherwise, it returns false. This method is helpful as it decreases the lines of code.

Which function is used to extract number from string in JavaScript?

The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. Regular expression for extracting a number is (/(\d+)/).


2 Answers

You can get it like this:

var suffix = 'comment_like_123456'.match(/\d+/); // 123456 

With respect to button:

$('.comment_like').click(function(){   var suffix = this.id.match(/\d+/); // 123456 }); 
like image 145
Sarfraz Avatar answered Oct 21 '22 17:10

Sarfraz


In your click handler:

var number = $(this).attr('id').split('_').pop(); 
like image 22
calebds Avatar answered Oct 21 '22 17:10

calebds