Search code examples
javascripthrefselectortarget

Modifying href selector to exclude anchor tags


Currently, this adds target="_blank" to all href that include .pdf in the URL, but also excludes URLs with www.fakewebsiteurl.com in it. I've been trying to modify it to also exclude anchor URLs, but I'm coming up short. What am I missing here?

document.addEventListener('DOMContentLoaded', function() {
    var links = document.querySelectorAll('a');
    links.forEach(function(link){
        var href = link.getAttribute('href');

        if (href.match(/\.pdf$/)
            || !href.match(/^\/www.fakewebsiteurl.com/)
            || !href.match(/\#$/)) {
                link.setAttribute('target', '_blank');
        }
    });
});

Solution

  • Remove the $ from your regex.

    !href.match(/\#/)