Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Get all but last item in array

Tags:

javascript

dom

This is my code:

 function insert(){   var loc_array = document.location.href.split('/');   var linkElement = document.getElementById("waBackButton");   var linkElementLink = document.getElementById("waBackButtonlnk");   linkElement.innerHTML=loc_array[loc_array.length-2];   linkElementLink.href = loc_array[loc_array.length];  } 

I want linkElementLink.href to grab everything but the last item in the array. Right now it is broken, and the item before it gets the second-to-last item.

like image 965
balexander Avatar asked Jul 09 '10 16:07

balexander


People also ask

How can you remove the last item in an array?

JavaScript Array pop() The pop() method removes (pops) the last element of an array. The pop() method changes the original array. The pop() method returns the removed element.

How do you find the last element of an array?

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.

How will you change the last element of an array in JS?

Use the array. prototype. splice() to Remove the Last Element From an Array JavaScript. The splice() method is used to change the array by removing or replacing the elements.

How do I find the last 5 elements of an array?

To get the last N elements of an array, call the slice method on the array, passing in -n as a parameter, e.g. arr. slice(-3) returns a new array containing the last 3 elements of the original array. Copied!


2 Answers

I’m not quite sure what you’re trying to do. But you can use slice to slice the array:

loc_array = loc_array.slice(0, -1); 
like image 173
Gumbo Avatar answered Oct 21 '22 09:10

Gumbo


Use pathname in preference to href to retrieve only the path part of the link. Otherwise you'll get unexpected results if there is a ?query or #fragment suffix, or the path is / (no parent).

linkElementLink.href= location.pathname.split('/').slice(0, -1).join('/'); 

(But then, surely you could just say:)

linkElementLink.href= '.'; 

Don't do this:

linkElement.innerHTML=loc_array[loc_array.length-2]; 

Setting HTML from an arbitrary string is dangerous. If the URL you took this text from contains characters that are special in HTML, like < and &, users could inject markup. If you could get <script> in the URL (which you shouldn't be able to as it's invalid, but some browser might let you anyway) you'd have cross-site-scripting security holes.

To set the text of an element, instead of HTML, either use document.createTextNode('string') and append it to the element, or branch code to use innerText (IE) or textContent (other modern browsers).

like image 38
bobince Avatar answered Oct 21 '22 10:10

bobince