简体   繁体   中英

Get the string between the last 2 / in regex in javascript

How can I get the strings between last 2 slashes in regex in javascript? for example:

stackoverflow.com/questions/ask/index.html => "ask"
http://regexr.com/foo.html?q=bar => "regexr.com"
https://www.w3schools.com/icons/default.asp => "icons"

You can use /\\/([^/]+)\\/[^/]*$/ ; [^/]*$ matches everything after the last slash, \\/([^/]+)\\/ matches the last two slashes, then you can capture what is in between and extract it:

 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]) ) 

You can solve this by using 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('/')

indexing after split()

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

I personally do not recommend using regex. Because it is hard to maintain

I believe that will do:

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

[^\\/]+ This matches all chars other than / . Putting this (?=\\/[^\\/]*$) in the sequence looks for the pattern that comes before the last / .

 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])); 

You can use (?=[^/]*\\/[^/]*$)(.*?)(?=\\/[^/]*$) . You can test it here: https://www.regexpal.com/

The format of the regex is: (positive lookahead for second last slash)(.*?)(positive lookahead for last slash).

The (.*?) is a lazy match for what's between the slashes.

references:

  1. Replace second to last "/" character in URL with a '#'

  2. RegEx that will match the last occurrence of dot in a string

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.

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