Alex Hawking
Alex Hawking

Reputation: 1245

Javascript get file name and type from path as string

I have a file drag and drop system which returns the whole path of the file as a string C:\Users\alexr\Desktop\filename.type. I can remove the home directory so I am left with Desktop\filename.type. How can I separate the path to the file (Desktop) to equal the variable path and the file name and type (filename.type) to equal the variable type.

I would like an answer is javascript or jQuery (Tho I doubt it will be needed)

Edit

Expected outcome:

Less say I had the following path Desktop\Folder\file.txt

I would like a variable path containing Desktop\Folder

And a variable file containing file.txt

Hope this clarifies things.

Upvotes: 0

Views: 2475

Answers (3)

Maniraj Murugan
Maniraj Murugan

Reputation: 9084

You need to split the file path like,

JSON.stringify(str).split("\\");

Here there is no need to alter you input, if you want to split the string that has backslash, then use,

.split("\\")

And the snippet as follows,

const str = "Desktop\filename.type";

const res = JSON.stringify(str).split("\\");
const result = JSON.parse(res).split(',');

const path = result[0];
const file = result[1];

console.log(path);
console.log(file);

Edit:

Okay, here is the reason why I used JSON.stringify(), because the string has backslash which ignores the next character after backslash so to get actual string, here I have used, JSON.stringify.. You can find the difference between both in the below console..

const str = "Desktop\filename.type";
console.log(str);
console.log(JSON.stringify(str))

console.log(JSON.stringify(str));

While you split the actual string like,

.split("\\"),

would result as a single array of string..

const str = "Desktop\filename.type";

console.log(str.split("\\"));

Upvotes: 2

Robert
Robert

Reputation: 10400

const str   = String.raw`Desktop\Folder\file.txt`;
const parts = str.split(`\\`);
const file  = parts.pop();
const path  = parts.slice(0).join(`\\`);

console.log(file)
console.log(path)

Note: I am using String.raw to preserve the forward slash, you may not need this

Upvotes: 1

mwilson
mwilson

Reputation: 12970

You can just use string substring to get the last index of the slash (since that's a good indicator where the filename.type will be.

The \\ is just to escape \

Example:

function splitPath(path) {
  return {
    path: path,
    file: path.substring(path.lastIndexOf('\\') + 1, path.length)
  };
}

const path = 'C:\\Users\\alexr\\Desktop\\filename.type';
console.log(splitPath(path));

Upvotes: 1

Related Questions