Aaron Bangerter
Aaron Bangerter

Reputation: 87

RegExp test jQuery

I'm using some jQuery/JavaScript to detect the path name of the page and assign an id to its link within the navigation. It essentially changes the link text from black to blue. Anyway, I've borrowed some of the code and I'm not advanced enough to figure out the RegExp test part, but when it passes the homepage as the path /, it assigns the id to all the links in the navigation (/index.html passes fine). Can someone help me figure out why the test is not working properly on the path name /?

$(function() { 
    var url = window.location.pathname,  
        urlRegExp = new RegExp(url.replace(/\/$/,'') + "$");

    $('.nav ul li a').each(function() {  
        if (urlRegExp.test(this.href.replace(/\/$/,''))) {        
            $(this).attr('id', 'selected'); 
        }
    });

    $(function() {
        if (url === "/index.html" || url === "/") {
            $('.nav').attr('id','homenav');
        }
    });
});

Upvotes: 1

Views: 243

Answers (2)

davidk
davidk

Reputation: 814

To explain your situation

  • when you are setting up urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); you are first removing the trailing slash. This is done by your regex /\/$/.

  • When you pass in / you will remove that slash and the resulting regex is /$/. This will match anything since all it is looking for is $ (which in regex indicates the end of the string). A solution will likely involve handling the / case specifically (as you indicated you have already done and the solution above does).

If you want to mess around with regex I have found that a good resource is http://gskinner.com/RegExr/

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173582

This should accomplish the same task:

var trailing_slash_re = /\/$/,
canon_url = location.pathname.replace(trailing_slash_re, '');

$('.nav ul li a').each(function() {
  var this_url = this.href.replace(trailing_slash_re, '');
  if (this_url.substr(-canon_url.length) == canon_url) {
    this.id = 'selected';
    return false; // don't process any others
  }
});

For each link it determines whether it ends with the canon_url. I'm jumping out of the loop once it has found an anchor that matches. This avoids multiple selected id's.

Upvotes: 2

Related Questions