Search code examples
jquerysplitdynamic-data

jquery check if string starts with and then extract it


I seem to have figured out how to do #1, but, not sure how to do the second part...

I have various p elements, each with a series of classes:

<p class="note cxid-45 contextual-item">Example</p>

I'm trying to determine if:

(1) the class list contains a class beginning with "cxid-" (2) if it does, I'd like to store the full class name

So, in the above markup, I'd like to store "cxid-45" in a variable: c

I managed this:

var pcl = $(this).attr("class").split(" ");

if(pcl.indexOf('cxid-') >= 0) {
  alert('found');  
  //This works, but not sure how to get the full string into the variable
  var c = ???;
} else {
  alert('not found');
  var c = '';
}

Solution

  • Try this

    var el=$('p[class*="cxid-"]');
    var c=el.length ? el.prop('class').match(/cxid-[^\s]+/g)[0] : 'Not Found!';
    alert(c); // If found then it'll alert the class name, otherwise 'Not Found!'
    

    DEMO.