0

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.

3
  • hopefully this is your want htmlgoodies.com/beyond/javascript/… Commented Aug 2, 2016 at 10:01
  • In what environment? Browser, Node.js, ... Commented Aug 2, 2016 at 10:03
  • yes,its sails and coffee js,while saving the image,i just need path as i mentioned to store in database Commented Aug 2, 2016 at 10:19

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

It will give result like this images\62f9a0f4-98b9-4dd0-8047-ed1a3cc306cf.png but i need \ before image
@TejasJain I've changed it to do that.
Thank you so much for you help.
1

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

2 Comments

It will give result like this images\62f9a0f4-98b9-4dd0-8047-ed1a3cc306cf.png but i need \ before image
You can just prepend that to the string. I will update the answer, but that is very trivial.
0
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);

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.