Home > Software design >  NodeJS - extract only the first part of an absolute path using regex (closed)
NodeJS - extract only the first part of an absolute path using regex (closed)

Time:08-20

Say we have a file path like the following...

This/is/my/path/to/file.txt

How would I get the first part of this file path and then get rid of the rest of the path, so I'm left with an output like below?

This/

I've managed to construct the following regex below...

var file = "this/is/my/path/to/file.txt"

var regex = file.match(/\/(. ?)\//)[1]
var str = file;
var output = str.match(regex);

console.log(output);

but it's not doing what I want, it's only returning the second part of the file path wrapped in square brackets as shown below...

[
 "is"
]

I am very new to Regex in JavaScript so I'm not sure where I'm going wrong, I've tried on this for about 4 hours, can anyone please help?

CodePudding user response:

you are doing one match and with the result you are doing a second match, I don't really understand, but in my solution there is just a regex to match anything except a slash plus one slash (that gives This/, just like in your example)

var file = "This/is/my/path/to/file.txt";

var regex = /[^/] \//;
var [output] = file.match(regex);

console.log(output);

  • Related