Reputation: 53
I have a file path for eg. "/abc/xyz/123/file.txt"
. How can I get the root directory ie."abc" from this path. I tried the following code:
var path = "/abc/xyz/123/file.txt";
var rootDir = path.split("/")[1];
This works for the above example. But the path can also be in below formats:
1. "abc/xyz/123/file.txt"
2. "\abc\xyz\123\file.txt"(backslash instead of forward slash path separator)
How to do this covering all the scenarios? Can this be done using regex
?
Upvotes: 0
Views: 2405
Reputation: 68383
try this match(/[^/\\]+/)
var reg = /[^/\\]+/
console.log( "abc/xyz/123/file.txt".match(reg) )
console.log( "/abc/xyz/123/file.txt".match(reg) )
console.log( "\\abc\\xyz\\123\\file.txt".match(reg) )
Upvotes: 3