Here is my JavaScript code so far:
var linkElement = document.getElementById("BackButton");
var loc_array = document.location.href.split('/');
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
linkElement.appendChild(newT);
Currently it takes the second to last item in the array from the URL. However I want to do a check for the last item in the array to be "index.html" and if so, grab the third to last item instead.
Another
ES6
only option would be to useArray.find(item, index)=> {...})
as follows:little practical value, posted to show that index is also available for your filtering logic.
In the event that your server serves the same file for "index.html" and "inDEX.htML" you can also use:
.toLowerCase()
.Though, you might want to consider doing this server-side if possible: it will be cleaner and work for people without JS.
Not sure if there's a drawback, but this seems quite concise:
or
Both will return
undefined
if the array is empty.EDITED:
Recently I came up with one more solution which I now think is the best for my needs:
With the above definition in effect I can now say:
The name "w" stands for "wrapper". You can see how you could easily add more methods besides 'last()' to this wrapper.
I say "best for my needs", because this allows me to easily add other such "helper methods" to any JavaScript built-in type. What comes to mind are the car() and cdr() of Lisp for instance.
Using ES6/ES2015 spread operator (...) you can do the following way.
Please notice that using spread operator and reverse we did not mutated original array, this is a pure way of getting a last element of the array.
I think the easiest and super inefficient way is: