bflemi3 bflemi3 - 1 month ago 12
Javascript Question

Match between occurrence of last slash in URL and hash

I'm trying to match between two characters, specifically the last part of a url but only between the last slash (

/
) and a hash (
#
).

http://example.com/path/to/thing#name


The match should return

thing


I'm partly there now. I can either get the whole string of the last part of the url, or everything before hash (
#
) but not both.

/([^\/]*?.*(?=#))/


Please see my regex101 for testing.

Answer

You are close but still overthinking it. This suffices:

/[^\/#]+(?=#|$)/

– a sequence of not-/ or # characters, where the next one should be #. You don't need to add parentheses to match it as a separate group, the match itself is correct. The final lookahead (?=#|$) makes it stop on either an intervening # or the end of the URL.

See regex101.