views:

91

answers:

8

What I want to accomplish is simple. I want a button's text to change depending on what page your on.

I start this by using the following:

var loc_array = document.location.href.split('/');

Now that I have the url and split it in an array I can grab certain directories depending on the position, like so:

if (loc_array[loc_array.length-1] == 'stations'){
  var newT = document.createTextNode("Stations & Maps");
}

Now this works if the directory is /test/stations/, however if someone types /test/stations/index.html then it doesn't work. How can you test against this without throwing in another if statement or using a similar conditional.

+1  A: 

I don't think string splitting is the best approach here. I would do it using RegEx.

var reStations = /\/stations(\/)?/i;
if (reStations.test(document.location.href))
    //Do whatever
Michal
That's going to give a false positive as soon as `'/stations'` appears in the query string or a trailing path part, though.
bobince
A: 
if (loc_array[4]=='stations')

if the url was http://www.example.com/test/stations/index.html, the values in the array would be:

  • [0] = "http:"
  • [1] = ""
  • [2] = "www.example.com"
  • [3] = "test"
  • [4] = "stations"
  • [5] = "index.html"
David
A: 

Not sure exactly what you're looking for, see if this fits:

var loc_array = document.location.href.split('/');

// this will loop through all parts
foreach (var i in loc_array) {
   switch (loc_array[i]) {
      case "stations":
         // do something
      break;

       // other cases
   }
}

   // or if you want to check each specific element
   switch (loc_array[0]) {
      case "stations": // assuming /stations/[something/]
         if (typeof loc_array[1] != 'undefined' && loc_array[1] == "something") {
            // do things
         }
      break;
    }
Rodrigo
A: 
if( document.location.href.split( "station" ).length > 1 ){ 
    //...
}
yulerz
A: 

I think I see where you are going with this... As someone stated above using a RegExp (regular expression) could be helpful... but ONLY if you had more than a single type of page to filter out (html/js/php/...), but for what it looks like you want to do. Try something like this:

var loc_array = document.location.href.split('/');
var i = loc_array.length-1;
var button_label = "default";

while(i>1)
{
    //checks to see if the current element at index [i] is html
    if(loc_array[i].indexOf(".html")>-1)
    {
        if(i>0)
        {
            var button_label = loc_array[i-1];
            break;
        }
    }
    i--;
}

alert(button_label);

What it does is:

  1. capture the current URL(URI)
  2. split it into an array
  3. starting from the END of the array and working BACKWARDS, look for the first element that contains the ".html" file identifier.
  4. We now know that the element BEFORE our current element contains the label we want to add to our buttons...
  5. You can then take the value and assign it wherever you need it.
  6. If you run out of elements, it has a default value you can use.

Not sure if this helps.....

I have tested the above code and it worked.

exoboy
+2  A: 

Actually both your examples work the same. /stations/ and /stations/index.html both get split into two strings; /stations/ has an empty string at the end. So length-2 would have worked. Where it wouldn't work would be /stations, which is up a level. But that wouldn't normally be an issue because if stations is a static directory, the web server will redirect the browser to /stations/ with the slash.

That won't happen if you're doing the routing yourself. If you're doing routing, it's not a good idea to index from the end of the list of path parts, are there might be any old rubbish there being passed as path-parameters, eg. /stations/region1/stationname2. In this case you should be indexing from the start instead.

If the application can be mounted on a path other than a root you will need to tell JavaScript the path of that root, so it can work out how many slashes to skip. You'll probably also need to tell it for other purposes, for example if it creates any images on the fly it'll need to know the root to work out the directory to get images from.

var BASE= '/path-to/mysite';
var BASELEVEL= BASE.split('/').length;
...

var pagename= location.pathname.split('/')[BASELEVEL];
// '/path-to/mysite/stations/something' -> 'stations'

I'm using location.pathname to extract only the path part of the URL, rather than trying to pick apart href with string or regex methods, which would fail for query strings and fragment identifiers with / in them.

(See also protocol, host, port, search, hash for the other parts of the URL.)

bobince
The issue I am having is I have m/station/rail but also /m/station and it's because of all the folder differences that this issue is arising.
Bry4n
Well `/m/station/rail` and `/m/station` should both be caught by `location.pathname.split('/')[1]==='station'`. When routing, index from the front of the URL, not the back.
bobince
A: 

You're example will show an empty string, cause the last item is empty; so you can simply make:

if (loc_array[loc_array.length-2] == 'stations')
{
    var newT = document.createTextNode("Stations & Maps");
}
JaKoPo
A: 

For simplicity's sake, supposing that there is an array of keywords (such as "station") that identify the pages, use a map and try to match its keys with the href string using indexOf,

var href = document.location.href ;
var identifiers = {
    "station": "Stations & Maps" , //!! map keys to result strings
    /* ... */
} ;

identifier_loop: //!! label to identify the current loop

    for(var n in identifiers) { //!! iterate map keys

        if( href.indexOf(n) !== -1 ) { //!! true if the key n in identifiers is in the href string

             var newT = document.createTextNode( identifiers[n] ) ; //!! create new text node with the mapped result string
             break identifier_loop ; //!! end iteration to stop spending ressources on the loop

        }

    }
FK82