2017-10-05 122 views

回答

2

您可以使用/\/([^/]+)\/[^/]*$/; [^/]*$匹配一切最后一个斜线,\/([^/]+)\/最后两条斜线匹配之后,那么你可以捕捉什么介于两者之间并解:

var samples = ["stackoverflow.com/questions/ask/index.html", 
 
       "http://regexr.com/foo.html?q=bar", 
 
       "https://www.w3schools.com/icons/default.asp"] 
 

 
console.log(
 
    samples.map(s => s.match(/\/([^/]+)\/[^/]*$/)[1]) 
 
)

1

您可以通过使用split()解决这个问题。拆分后

let a = 'stackoverflow.com/questions/ask/index.html'; 
let b = 'http://regexr.com/foo.html?q=bar'; 
let c = 'https://www.w3schools.com/icons/default.asp'; 

a = a.split('/') 
b = b.split('/') 
c = c.split('/') 

索引()

console.log(a[a.length-2]) 
console.log(b[b.length-2]) 
console.log(c[c.length-2]) 

我个人不建议使用正则表达式。因为它是很难维持

0

我相信会做:

[^\/]+(?=\/[^\/]*$)

[^\/]+这比/以外的所有字符相匹配。将此(?=\/[^\/]*$)放入序列中查找最后/之前的模式。

var urls = [ 
 
    "stackoverflow.com/questions/ask/index.html", 
 
    "http://regexr.com/foo.html?q=bar", 
 
    "https://www.w3schools.com/icons/default.asp" 
 
    ]; 
 

 
urls.forEach(url => console.log(url.match(/[^\/]+(?=\/[^\/]*$)/)[0]));

相关问题