JasperZelf
JasperZelf

Reputation: 2844

Regex to get a specific part of an URL

Say I've got an URL:

http://www.example.com/foo/bar/yes_no_no.html

I'm looking for a regex that can extract all the characters of the filename up to the first underscore. So in the above URL I want to extract "yes".

So far I managed to get the whole "yes_no_no" bit using:

/([^\/]+)(?=\.\w+$)/, but I can't seem to get it to only match "yes".

Upvotes: 1

Views: 53

Answers (1)

Michał Perłakowski
Michał Perłakowski

Reputation: 92471

Try this:

/\/([^_\/]+)_?[^\/]*\.[a-z]+$/

Example:

console.log('http://www.example.com/foo/bar/yes_no_no.html'.match(/\/([^_\/]+)_?[^\/]*\.[a-z]+$/)[1])
console.log('http://www.example.com/foo/bar/yes.html'.match(/\/([^_\/]+)_?[^\/]*\.[a-z]+$/)[1])

Upvotes: 3

Related Questions