简体   繁体   中英

How to get the last folder name and file name from a path using JavaScript?

how can i get the last folder name and file name from a full path,I need a solution for this.


Example:

d:\folder1\folder2\assets\images\62f9a0f4-98b9-4dd0-8047-ed1a3cc306cf.png

In my case,I just need \\images\\62f9a0f4-98b9-4dd0-8047-ed1a3cc306cf.png from the path in Javascript.

Not the ideal solution, but gets the work done. I had to escape the \\ while creating the string

var arr = "d:\\folder1\\folder2\\assets\\images\\62f9a0f4-98b9-4dd0-8047-ed1a3cc306cf.png".split("\\");

    var length = arr.length, path = "\\" + arr[length-2] + "\\" + arr[length-1];

    console.log(path);

This should do it:

 var str = "d:\\\\folder1\\\\folder2\\\\assets\\\\images\\\\62f9a0f4-98b9-4dd0-8047-ed1a3cc306cf.png"; var ret = str.split("\\\\").reduce((p,c,i,arr) => {if(i >= arr.length - 2){return (p?("\\\\"+p+"\\\\"):"")+c}}); console.log(ret); 

var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
var indxend = url.lastIndexOf('/')-1
var folderName =url.substring(0,indxend).substring(url.substring(0,indxend).lastIndexOf('/')+1);

Give this a go:

 var path = 'd:\\\\folder1\\\\folder2\\\\assets\\\\images\\\\62f9a0f4-98b9-4dd0-8047-ed1a3cc306cf.png'; var parts = path.split('\\\\'); var file = parts.pop(); var fileAndPar = parts.pop() + '\\\\' + file; console.log(fileAndPar); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM