我确信堆栈溢出可能有类似的东西,但我找不到任何东西,并且对于非常简单的东西感到非常沮丧.
我需要使用javascript捕获部分URL(类似于url重写引擎).
网址结构:
http://example.com/constant/CAPTURETHIS
http://example.com/constant/CAPTURETHIS/
http://example.com/constant/CAPTURETHIS#noise
http://example.com/constant/CAPTURETHIS/#noise
Run Code Online (Sandbox Code Playgroud)
我需要返回所有3个senerios的CAPTURETHIS文本
JavaScript支持使用字符串对象的match方法或正则表达式对象的exec方法检索正则表达式捕获组:
var captureThis = url.match(/^http:[/][/]example[.]com[/]constant[/]([^/]+)/)[1];
var captureThis = /^http:[/][/]example[.]com[/]constant[/]([^/]+)/.exec(url)[1];
Run Code Online (Sandbox Code Playgroud)
但是对于你的例子,我几乎想知道使用字符串对象的split方法是否更简单:
var captureThis = url.split(/[/]/)[4];
Run Code Online (Sandbox Code Playgroud)