开发者

jQuery and regex for adding icons to specific links?

开发者 https://www.devze.com 2022-12-28 10:33 出处:网络
I\'m using jQuery to add icons to specific links, e.g. a myspace icon for sites starting with http://myspace.com etc.

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://开发者_C百科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!


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']")


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");
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消