0

I'm trying to add css to a div, when the website have /category or /blog in url.

follows my code:

    var expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
    var regex = new RegExp(expression);
    var paths = ['/blog', '/category'];

  for (i = 0; i < paths.length; i++) {
      if (paths[i].match(regex) )
            {
             console.log("Successful match");
             $('.page-title').css('bottom', '-100px');
            } else {
             console.log("No match");
            }
    }

The problem is this return false always, seems to don't getting just the /blogor /category i need to put the css just when have this two parts in url, I think this regex is wrong or something is missing, someone can help?

Wagner Moreira
  • 1,033
  • 1
  • 16
  • 40
  • See [What is the best regular expression to check if a string is a valid URL?](http://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url) – Braj Aug 12 '14 at 17:15
  • 1
    Can you put sample data for what you consider valid and invalid urls? – Federico Piazza Aug 12 '14 at 17:16
  • 1
    If you only have to search for specific strings in the URL, you could use `indexOf` instead – Salman Aug 12 '14 at 17:16
  • Where in this script is the url to be tested passed in? – Bergi Aug 12 '14 at 17:18
  • 1
    Notice that `expression` is already `instanceof RegExp` (the regex literal yields a regex object), there is no need to create a `regex` variable using the `new RegExp` constructor. – Bergi Aug 12 '14 at 17:20

2 Answers2

1

That Regex looks like it will match a full URL ... not a path like you're doing here. Plus, there's no place in this code that references the current page you're on.

Something like this should work:

if (location.href.match(/\/(blog|category)/)) {
  console.log("Successful match");
  $('.page-title').css('bottom', '-100px');
} else {
  console.log("No match");
}
supercleanse
  • 161
  • 1
  • 4
1

This regex validates if the strings on the array are on format xxxxx.yyyy/zzzzz. And none of them do.

Also... even if the strings were in the expected format, you would pass all valid URLs, instead of passing only the ones you want (blog and category).

Note that you are not validating the actual URL anywhere.

Perhaps what you want is something like:

var url = window.location.href;
var paths = ['/blog','/category']

for (i = 0; i < paths.length; i++) {
    if (url.indexOf(paths[i]) > 0){
        console.log("Successful match");
        $('.page-title').css('bottom', '-100px');
    } else {
        console.log("No match");
    }
}
Matheus208
  • 1,289
  • 2
  • 13
  • 26