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

javascript, jquery, regex

Solution

$("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/

Problem

``` $("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/

Original source