Get a substring of a string using jQuery

I have a div with the following classes:

form-group val-presence-text val-type-pos-int val-length-10 has-success has-feedback 

I want to get 10 from the class name val-length-10 . I tried various methods, but none of them work for a multi-class dynamic attribute like this. In addition, 10 can be any positive integer, and the class can be located anywhere in the class group.

Any ideas?

0
javascript jquery substring html
May 01 '14 at 15:10
source share
4 answers

You can use this:

 var val_length = $('div').attr("class").match(/val-length-(\d+)/)[1]; 
+3
May 01 '14 at 15:12
source share

One possible solution:

 var n = (this.className.match(/val-length-(\d+)/) || []).pop(); 

Or in context:

 $('[class*="val-length-"]').each(function() { var n = (this.className.match(/val-length-(\d+)/) || []).pop(); console.log(n); }); 
+2
May 01 '14 at 15:13
source share

Assuming this is a "val-length" that never changes, but just an integer at the end, you should be able to do this:

 //get an array of classes on a specific element var classList =$('#elementId').attr('class').split(/\s+/); //loop through them all $.each( classList, function(index, item){ //check if any of those classes begin with val-length- if (item.indexOf('val-length' === 0) { console.log(item.substring(11)) } }); 
0
May 01 '14 at 15:19
source share

Try it...

 $("div[class*=val-length-]").each(function() { var s = this.className; var length = 0; $(s.split(" ")).each(function() { if (this.search("val-length-") === 0) { length = this.substr(11); } }); console.log(length); }); 

It will find the corresponding div and pull the value for you.

-one
May 01 '14 at 15:15
source share



All Articles