Noranda Brown
Noranda Brown

Reputation: 99

Obtain 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 the 10 from the val-length-10 class name. I've tried various methods, but none seem to work for a dynamic multi-class attribute such as this. In addition, the 10 could be any positive integer and the class could be located anywhere within the group of classes.

Any ideas?

Upvotes: 0

Views: 304

Answers (4)

Amit Joki
Amit Joki

Reputation: 59232

You can use this:

var val_length = $('div').attr("class").match(/val-length-(\d+)/)[1];

Upvotes: 3

Jonathon Blok
Jonathon Blok

Reputation: 749

Assuming that the it is 'val-length' that never changes and just the integer on the end of it, 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))
    }
 });

Upvotes: 0

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

Try this...

$("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 relevant div and pull the value for you.

Upvotes: -1

VisioN
VisioN

Reputation: 145398

One possible solution:

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

Or in the context:

$('[class*="val-length-"]').each(function() {
    var n = (this.className.match(/val-length-(\d+)/) || []).pop();
    console.log(n);
});

Upvotes: 2

Related Questions