2

I have this script:

<script type="text/javascript">
$(document).ready(function() {

var url = location.pathname;

  if ("url:contains('message')") {
    $("a#none").attr("class","active");
  }

});        
        </script>

It nicely adds the class active to the url. However, it add the class active to the url even if the url does not contain the path message. What am I doing wrong?

  • 2
    `"url:contains('message')"` in your code is just a string which will always amount to `true`. You are looking for `indexOf` (http://stackoverflow.com/questions/1789945/method-like-string-contains-in-javascript) – Pekka Feb 17 '13 at 21:06

1 Answers1

5

That's because strings are truthy and :contains is a jQuery selector that doesn't do anything in your code, you can use indexOf method of the String object:

if (url.indexOf('message') > -1) {
    // $("#none").addClass("active");
}
Ram
  • 143,282
  • 16
  • 168
  • 197
  • Awesome thanks! Worked perfectly :) What does the `-1` actually do? –  Feb 17 '13 at 21:14
  • @tech0925: If no match is found -1 is returned. For more details see the [**MDN on IndexOf**](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf) – Nope Feb 17 '13 at 21:17
  • @tech0925 You are welcome, if the `message` is at the beginning of the string, `indexOf` returns `0` which is a falsy value and then the `if` block is not executed. – Ram Feb 17 '13 at 21:19