javascript get last index code example

Example 1: javascript get last element of array

var foods = ["kiwi","apple","banana"];
var banana = foods[foods.length - 1]; // Getting last element

Example 2: Javascript get last item in array

var colors = ["red","blue","green"];
var green = colors[colors.length - 1]; //get last item in the array

Example 3: js last index of

const str = "Users/Edit/12345";
let idx = str.lastIndexOf("/"); // returns 10
idx = str.lastIndexOf("x"); // returns -1

idx = str.lastIndexOf("Edit") // returns 6
idx = str.lastIndexOf("edit") // returns -1 -- case sensitive

// add "from" parameter
// the search happens backwards, starting at the provided from parameter
idx = str.lastIndexOf("s"); // returns 4
idx = str.lastIndexOf("s", 3); // returns 1

Example 4: last index of array js

array.lastIndexOf(searchElement[, fromIndex]);

Example 5: javascript array last element

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);

Example 6: javascript get last element of array

console.log(2)