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

184
Views
Regex to get substring between first and last occurence

Assume there is the string

just/the/path/to/file.txt

I need to get the part between the first and the last slash: the/path/to

I came up with this regex: /^(.*?).([^\/]*)$/, but this gives me everything in front of the last slash.

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

0

Don't use [^/]*, since that won't match anything that contains a slash. Just use .* to match anything:

/(.*?)\/(.*)\/(.*)/

Group 1 = just, Group 2 = the/path/to and Group 3 = file.txt.

about 4 years ago · Juan Pablo Isaza Report

0

The regex should be \/(.*)\/. You can check my below demo:

const regex = /\/(.*)\//;
const str = `just/the/path/to/file.txt`;
let m;

if ((m = regex.exec(str)) !== null) {
    console.log(m[1]);
}

about 4 years ago · Juan Pablo Isaza Report

0

This regex expression will do the trick

const str = "/the/path/to/the/peace";
console.log(str.replace(/[^\/]*\/(.*)\/[^\/]*/, "$1"));

[^\/]*\/(.*)\/[^\/]*

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!