简体   繁体   English

在 Javascript 中提取字符串的更好方法

[英]Better way to extract a string in Javascript

I've a string which is我有一个字符串

xyz.com/test/classified/electronics/home-audio-turntables/amplifiers/new/ . 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/我想从上面的字符串中提取以下值,即/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我想你要找的是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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM