Alex Rivera | Logout

JavaScript - Get all but last item in array

Asked 2010-07-09T16:01:40.643
85

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.

Edit
Report

2 Answers

126

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

let loc_array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
loc_array = loc_array.slice(0, -1)
console.log(loc_array)

answered 2010-07-09T16:07:55.733
74

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

answered 2010-07-09T16:30:15.237

Your Answer