tags:

views:

33

answers:

2

I'm using jQuery to add icons to specific links, e.g. a myspace icon for sites starting with http://myspace.com etc.

However, I can't figure out how to use regular expressions (if that's even possible here), to make jQuery recognize the link either with or without "www." (I'm very bad at regular expressions in general).

Here are two examples:

    $("a[href^='http://www.last.fm']").addClass("lastfm").attr("target", "_blank");
    $("a[href^='http://livejournal.com']").addClass("livejournal").attr("target", "_blank");

They work fine, but I now I want the last.fm link to work with http://last.fm, http://www.last.fm and http://www.lastfm.de. Currently it only works for www.last.fm.

I also would like to make the livejournal link work with subdomains links like http://username.livejournal.com

How can I do that? Thanks in advance!

+1  A: 

You could do something like this:

var icons = {
    "last.fm": "lastfm",
    "lastfm.de": "lastfm",
    "livejournal.com": "livejournal"
};
$("a[href]").each(function(){
    var match;
    if ((match = this.href.match(/^https?:\/\/(?:\w+\.)*(\w+\.\w+)(?:$|\/)/)) && icons.hasOwnProperty(match[1])) {
        $(this).addClass(icons[match]).attr("target", "_blank");
    }
});
Gumbo
Thank you! I've tried this, but it doesn't seem to work. No classes added :/
rayne
@rayne: I fixed some bugs. It should work now.
Gumbo
+1  A: 

First, Gumbo's answer is best if you want strict matching, regex is the way to go. If you're a bit looser and just need to match, you can stick with selectors. For the first you can use multiple selectors:

$("a[href^='http://last.fm'], a[href^='http://www.last.fm'], a[href^='http://www.lastfm.de']")

For the last, you could switch to a contains selector, like this:

$("a[href*='livejournal.com']")
Nick Craver
Thank you for your answer! I've tried the contains selector, but for some reason it's not working :/ `$("ul a[href~='livejournal.com']").addClass("livejournal").attr("target", "_blank");`
rayne
@rayne - Opps, my fault, that should be `*=` not `~=`, try changing it in your selector...updated the answer to show the same.
Nick Craver
Exactly what I needed, thank you so much! :)
rayne