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.
1) Using the array length property The length property returns the number of elements in an array. Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed.
The last element of an array is at position size - 1.
To get the first and last elements of an array, access the array at index 0 and the last index. For example, arr[0] returns the first element, whereas arr[arr. length - 1] returns the last element of the array.
You can access the last value in an object directly, by using the Object. values() method to get an array of the object's values and calling the pop() method on the result, e.g. Object. values(obj). pop() .
if (loc_array[loc_array.length - 1] === 'index.html') { // do something } else { // something else }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With