I've a string which is
xyz.com/test/classified/electronics/home-audio-turntables/amplifiers/new/
.
I want to extract following value from above string ie, /classified/electronics/home-audio-turntables/amplifiers/
I'm able to achieve with below logic but is there a better way than this? Appreciate suggestions
window.location.href.split('test')[1].split('/new')[0]
I think what you are looking for is window.location.pathname
In case of testing:
window.location.pathname.replace(/^(\/test)?/, '')
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.