JasperZelf JasperZelf - 3 months ago 9
Javascript Question

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".

Answer

Try this:

/\/([^_\/]+)_/

Example:

console.log('http://www.example.com/foo/bar/yes_no_no.html'.match(/\/([^_\/]+)_/)[1])