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

219
Views
Better way to extract a string in Javascript

I have a string which is

xyz.com/test/classified/electronics/home-audio-turntables/amplifiers/new/.

I want to extract following value from above string i.e., /classified/electronics/home-audio-turntables/amplifiers/

I'm able to achieve this with the code below but is there a better way than this? Appreciate suggestions

window.location.href.split('test')[1].split('/new')[0]
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

A regular expression can match what comes between.

const str = 'xyz.com/test/classified/electronics/home-audio-turntables/amplifiers/new/';

const result = str.match(/test(\/.*?\/)new/)[1];
console.log(result);

Or with lookbehind

const str = 'xyz.com/test/classified/electronics/home-audio-turntables/amplifiers/new/';

const result = str.match(/(?<=test)\/.*?\/(?=new)/)[0];
console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

I think what you are looking for is window.location.pathname

In case of testing:

window.location.pathname.replace(/^(\/test)?/, '')
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!