Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Add file type class to links for ANY file type

$("a[href $='.pdf']" ).addClass("linkIconPDF");
$("a[href *='.pdf#']").addClass("linkIconPDF");
$("a[href *='.pdf;']").addClass("linkIconPDF");
$("a[href *='.pdf?']").addClass("linkIconPDF");

$("a[href $='.txt']" ).addClass("linkIconTXT");
$("a[href *='.txt#']").addClass("linkIconTXT");
$("a[href *='.txt;']").addClass("linkIconTXT");
$("a[href *='.txt?']").addClass("linkIconTXT");

So far so good, but how can it be simplified to match any file type?

Is it possible to do some regex grouping to match all possible file types like this?

$("a[href $='.([a-zA-Z0-9]{2,4})']" ).addClass("linkIcon$1");

Test script: http://jsfiddle.net/k2jqn/

like image 506
Martin Avatar asked Nov 23 '12 15:11

Martin


3 Answers

$("a").each(function(){
    var match = this.href.match(/\.([a-zA-Z0-9]{2,4})([#;?]|$)/);
    if(match){
        $(this).addClass("linkIcon" + match[1]);
    }
});

Demonstration: http://jsfiddle.net/k2jqn/4/

like image 142
Asad Saeeduddin Avatar answered Nov 20 '22 18:11

Asad Saeeduddin


You can simply use the wildcard selector:

$("a[href*='.pdf']" ).addClass("linkIconPDF");
$("a[href*='.txt']" ).addClass("linkIconTXT");

It selects the links in a wildcard way.

like image 1
Praveen Kumar Purushothaman Avatar answered Nov 20 '22 17:11

Praveen Kumar Purushothaman


Why not try this

$("a[href $='.$']" ).addClass("linkIconANYFILE");
like image 1
jsertx Avatar answered Nov 20 '22 16:11

jsertx