user357086
user357086

Reputation: 404

Regular expression to determine website root

I have following url's and all these url are considered root of the website, how can I use javascript location.pathname using regex to determine pattern below, as you'll notice the word "site" is repeating in this pattern..

 http://www.somehost.tv/sitedev/
 http://www.somehost.tv/sitetest/
 http://www.somehost.tv/site/

 http://www.somehost.tv/sitedev/index.html
 http://www.somehost.tv/sitetest/index.html
 http://www.somehost.tv/site/index.html

I am attempting to display jQuery dialog only and only if the user is at the root of the website.

Upvotes: 0

Views: 559

Answers (3)

Moritz Roessler
Moritz Roessler

Reputation: 8631

If you do not explicitly need a Regular Expression for this

You also could do for example

  • Fill an array with your urls
  • Loop over a decreasing substring of
    • the shortest element.
  • Comparing it against
    • the longest element.
  • Until they match.

 var urls = ["http://www.somehost.tv/sitedev/",
 "http://www.somehost.tv/sitetest/",
 "http://www.somehost.tv/site/",
 "http://www.somehost.tv/sitedev/index.html",
 "http://www.somehost.tv/sitetest/index.html",
 "http://www.somehost.tv/site/index.html"]

     function getRepeatedSub(arr) {
         var srt = arr.concat().sort();
         var a = srt[0];
         var b = srt.pop();
         var s = a.length;
         while (!~b.indexOf(a.substr(0, s))) {
             s--
         };
         return a.substr(0, s);
     }
 console.log(getRepeatedSub(urls)); //http://www.somehost.tv/site   

Heres an example on JSBin

Upvotes: 0

Julian H. Lam
Julian H. Lam

Reputation: 26134

Simply use the DOM to parse this. No need to invoke a regex parser.

var url = 'http://www.somesite.tv/foobar/host/site';
    urlLocation = document.createElement('a');

urlLocation.href = url;
alert(urlLocation.hostname);    // alerts 'www.somesite.tv'

Upvotes: 2

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

A complete pattern, including protocol and domain, could be like this:

/^http:\/\/www\.somehost\.tv\/site(test|dev)?\/(index\.html)?$/

but, if you're matching against location.pathname just try

/^\/site(test|dev)?\/(index\.html)?$/.test(location.pathname)

Upvotes: 0

Related Questions