External links in new window..wild card regexp

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tjtryutyu
    New Member
    • Nov 2007
    • 3

    External links in new window..wild card regexp

    I know very little javascript. Nonetheless, I found some example code that opens links into a new window if they contain "external" on the "rel attribute. For example:
    Code:
    <a href="http:example.com" rel="external">this link opens in a external window</a>
    I later hacked the code so it works it "nofollow" is added to the "rel" attribute like:
    Code:
    <a href="http:example.com" rel="external nofollow">this link opens in a external window with nofollow</a>
    The following is the contents on my original javascript called external.js
    Code:
    function externalLinks() {
     if (!document.getElementsByTagName) return;
     var anchors = document.getElementsByTagName("a");
     for (var i=0; i<anchors.length; i++) {
       var anchor = anchors[i];
       if (anchor.getAttribute("href") &&
           ((anchor.getAttribute("rel") == "external nofollow") || (anchor.getAttribute("rel") == "external")))
    
    
         anchor.target = "_blank";
     }
    }
    window.onload = externalLinks;
    Now I want to use a regular expression to match different possibilities of the "rel" attribute.
    I found a good tutorial on javascript regexp at:
    Javascript RegExp tutorial

    However no hacks I have tried based on the tutorial have worked.
    I have tried the following:
    Code:
    (anchor.getAttribute("href") &&  /(.)*(external)(.)*/i.test(anchor.getAttribute("rel")) )
    and
    Code:
    (anchor.getAttribute("href") &&  anchor.getAttribute("rel") == /(.)*(external)(.)*/i)


    Can anybody help!
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    You can use any of the String search methods, e.g. indexOf, match, search. See this reference.

    Comment

    • tjtryutyu
      New Member
      • Nov 2007
      • 3

      #3
      Originally posted by acoder
      You can use any of the String search methods, e.g. indexOf, match, search. See this reference.
      Thanks Acoder!

      IndexOf worked like a charm!
      BTW here is my new script:

      Code:
      function externalLinks() {
       if (!document.getElementsByTagName) return;
       var anchors = document.getElementsByTagName("a");
       for (var i=0; i<anchors.length; i++) {
         var anchor = anchors[i];
         if (anchor.getAttribute("href") && anchor.getAttribute("rel").indexOf("external") != -1)
      
      
           anchor.target = "_blank";
       }
      }
      window.onload = externalLinks;

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

        #4
        You're welcome. Glad you've got it working.

        Comment

        Working...