Here is my JavaScript code so far:
var linkElement = document.getElementById(“BackButton”);
var loc_array = document.location.href.split(‘/’);
var index = loc_array.length - 1;
var newT;
if (loc_array[index] === “index.html”) {
index = loc_array.length - 3;
}
newT = document.createTextNode(unescape(capWords(loc_array[index])));
linkElement.appendChild(newT);
Currently, the code takes the second-to-last item in the array from the URL. However, I want to add a check for the last item in the array to be “index.html”. If this condition is met, I want to grab the third-to-last item instead.
Hey Sakshi,
I understand your query and here’s how you can rewrite the provided answer using ES2022 features:
if (loc_array[loc_array.length - 1] === ‘index.html’) {
// do something
} else {
// something else
}
// Using ES2022 Array.at()
if (loc_array.at(-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(). However, it’s worth considering doing this server-side if possible for cleaner and more reliable functionality, especially for users without JavaScript.
Hey Sakshiku,
It’s worth noting that while adding a last() method to the Array prototype can be convenient, it’s considered best practice to avoid modifying built-in prototypes. Using ES6 modules to define utility functions like last() is a more modern and modular approach.
// Using prototype to add a last() method to arrays
Array.prototype.last = function() {
return this[this.length - 1];
}
// Using ES6 module export to define a last function
export function last(array) {
return array[array.length - 1];
}
Hey Ian,
Both of these methods provide a concise way to get the last element of an array. However, they will return undefined if the array is empty.
// Using slice and array access
arr.slice(-1)[0];
// Using slice and pop
arr.slice(-1).pop();