简体   繁体   中英

How to match a url in javascript with regexp

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 /blog or /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?

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");
}

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");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM