修改 href 选择器以排除锚标记

Modifying href selector to exclude anchor tags

目前,这会将 target="_blank" 添加到 URL 中包含 .pdf 的所有 href,但也会排除 URL www.fakewebsiteurl.com在里面。我一直在尝试修改它以排除锚点 URLs,但我做空了。我在这里错过了什么?

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');
        }
    });
});

术语 "anchor URLs" 可以有几种解释。

如果您正在讨论以 # 开头的值,您可能需要 /^#/.

的正则表达式

如果您谈论的值包含 #,您可能需要 /#/

的正则表达式

如果您谈论的值只是 #,您可能需要 /^#$/

的正则表达式

从您的正则表达式中删除 $。

!href.match(/\#/)