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/
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.
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.
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.
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.
Try:
var sourcePath="/abc/def/ghi";
var lastIndex=sourcePath.lastIndexOf("/");
var requiredPath=sourcePath.slice(0,lastIndex+1);
Output: /abc/def/
Try:
var path = "/bar/foo/moo/";
var split = path.split("/");
var x = split.slice(0, split.length - 2).join("/") + "/";
alert(x);
Demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With