Skip to content Skip to sidebar Skip to footer

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 nam

Solution 1:

You can use this:

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

Solution 2:

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);
});

Solution 3:

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 elementvar 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))
    }
 });

Solution 4:

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.

Post a Comment for "Obtain A Substring Of A String Using Jquery"