Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
NodeJS - extract only the first part of an absolute path using regex (closed)

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!