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]
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);
I think what you are looking for is window.location.pathname
In case of testing:
window.location.pathname.replace(/^(\/test)?/, '')