patternjavascriptCritical
Get the last item in an array
Viewed 0 times
arraylasttheitemget
Problem
Here is my JavaScript code so far:
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
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.Solution
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.
EDIT - ES-2022
Using ES-2022
Array.at(), the above may be written like this:if (loc_array.at(-1) === 'index.html') {
// do something
} else {
// something else
}Code Snippets
if (loc_array[loc_array.length - 1] === 'index.html') {
// do something
} else {
// something else
}if (loc_array.at(-1) === 'index.html') {
// do something
} else {
// something else
}Context
Stack Overflow Q#3216013, score: 2584
Revisions (0)
No revisions yet.