Multiple filters? Should be simple

I have an element that has a class like posts-6 or posts-3, among other classes. I need the numerical value at the end of posts-*.

So this is how I’m approaching it:

const self = $(this);
      var itemNumber;
      if(self.is("[class*='posts-'")) {
        itemNumber = self.attr("class").split(' ').filter(function(value) {
          return value.indexOf("posts-") > -1;
        });
        // itemNumber = itemNumber.split("-").pop();
        console.log(itemNumber);
        console.log(typeof itemNumber);
      }

My thought was to modify the filter function to .split("-").pop() but I’ve tried that and failed. I tried filtering the returned value but the filter result is no longer a string so I think it’s giving me an error because of that. How can I accomplish this? This seems to be so simple yet I’m struggling on the best way to go about it.

let itemNumber = String(self.attr('class')).match(/^posts-(\d+)$/)[1];
2 Likes

I had gotten it working like this

if(self.is("[class*='posts-'")) {
        itemNumber = self.attr("class").split(' ').filter(function(value) {
          return value.indexOf("posts-") > -1;
        });
        itemNumber = itemNumber.toString().split("-").pop();
      }

but your seems much better :slight_smile: thank you

Edit -

main.js?1660329972:21 Uncaught TypeError: Cannot read properties of null (reading '1')
let itemNumber;
      if(self.is("[class*='posts-'")) {
        itemNumber = String(self.attr('class')).match(/^posts-(\d+)$/)[1];
      }

Weird. I tried the following in a REPL and it works just fine

let a = "posts-6";

console.log(String(a).match(/^posts-(\d+)$/)[1]);

// outputs 6

(casting a to string isn’t strictly necessary here, but it is when using an attribute I found, so I’ve put it there to be sure that works too)

“among other classes”. your match is doing a wholestring match. take the ^ and $ out. (or add extender wildcards to the ends, either way)

2 Likes

Jackpot! Thank you. That worked splendidly. Great eye, catching that little tidbit of information.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.