sesodesa
sesodesa

Reputation: 1603

Choose all links whose targets don't have suffixes using jQuery

How could I perform the selection desribed in the title? I think it should be fairly safe to assume that such links don't have anything like .asdafasdfsaf, .html or .zip at the end of their targets, so I tried the following:

var links = jQuery("a:not([href$='.*'])") // Period as is
var links = jQuery("a:not([href$='\.*'])") // One escape
var links = jQuery("a:not([href$='\\.*'])") // Two escapes

None of these seem to really do anything in terms of preventing the non-desired links from being selected, however. How could one fix this?

EDIT:

This attempt with RegExes didn't work:

function has_suffix (target_string) {
   regex = RegExp("(\/.*\..*)$");
   if ( regex.test(target_string) ) {
     return true;
   } else {
     return false;
   }

var links = jQuery("a").filter(
  function () {
    target = $(this).attr("href")
    console.log(target)
    return $(true,this) === has_suffix(target);
  });

Testing the RegExp in the console seems to do produce the results that I want, but actually utilizing the has_suffix function in the filter is giving me a headache. The documentation for filter is of no use to me; it's not clear enough in its examples.

Upvotes: 0

Views: 37

Answers (1)

BoltClock
BoltClock

Reputation: 723448

You can simply return the result of has_suffix() directly, as the filter function already runs once for every element that is matched:

var links = jQuery("a").filter(
  function () {
    target = $(this).attr("href")
    console.log(target)
    return has_suffix(target);
  });

Upvotes: 1

Related Questions