Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to array then remove last element

I have the strings below and I am trying to remove the last directory from them but I cant seem to get the grasp of it.

JavaScript

var x = path.split("/")
alert(path +' = ' +x.slice(0, -1));

Expected Result

/foo/bar/ = /foo/
/bar/foo/ = /bar/
/bar/foo/moo/ = /bar/foo/
like image 624
Joe Avatar asked Aug 20 '11 07:08

Joe


People also ask

How can I remove the last item in an array?

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 insert and remove the last element of an array?

To remove the last element or value from an array, array_pop() function is used. This function returns the last removed element of the array and returns NULL if the array is empty, or is not an array.

How do you remove the last string of an array?

To remove the last element of an array, we can use the Enumerable. SkipLast() method from System. Linq in C#. The SkipLast() takes the count as an argument and returns the new collection of elements from the source array by removing count elements from the end of a collection.

How do you remove the last two elements of an array?

Use the splice() method to remove the last 2 elements from an array, e.g. arr. splice(arr. length - 2, 2) . The splice method will delete the 2 last elements from the array and return a new array containing the deleted elements.


2 Answers

Try:

var sourcePath="/abc/def/ghi";
var lastIndex=sourcePath.lastIndexOf("/");
var requiredPath=sourcePath.slice(0,lastIndex+1);

Output: /abc/def/

like image 125
SHIVA Avatar answered Sep 19 '22 20:09

SHIVA


Try:

var path = "/bar/foo/moo/";
var split = path.split("/");
var x = split.slice(0, split.length - 2).join("/") + "/";
alert(x);

Demo.

like image 24
karim79 Avatar answered Sep 19 '22 20:09

karim79