Ben393 Ben393 -4 years ago 235
CSS Question

If window.location.href does not match a certain string, add css class to element

I am new to javascript/jQuery and am trying to add a css class to an element if the page's url does not match one of three strings. I cannot these lines of my code to work.

if (window.location.href.match(/(interests|ideas|art)/) > -1) {

Any ideas? Is my syntax incorrect?


It seems like the answers everyone has given me should be working, but they aren't. Maybe other lines of my code are conflicting:

$(document).ready(function() {
if (|ideas|art)/) > -1) {
if (window.location.href.match(/(interests)/) != null) {
if (window.location.href.match(/(ideas)/) != null) {
if (window.location.href.match(/(art)/) != null) {

My site is The link,
on this main page is what needs the class
; the script does not work on this page. The script on the other pages, interests, ideas and photography work.

Answer Source

For what you are doing, you want to use .search() not .match(). The return value for .search() is the index of the first match, or -1 if there is not a match. The return value for .match() is:

An Array containing the entire match result and any parentheses-captured matched results; null if there were no matches.

Fixing the above issue, and given that you have stated you want to add the class when the URL does not match, the code should be:

if (|ideas|art)/) === -1) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download