Search code examples
javascriptregexurl-parsing

URL Pattern Matching issue, .+ matches all after


I am matching up stored URLs to the current URL and having a little bit of an issue - the regex works fine when being matched against the URL itself, but for some reason all sub-directories match too (when I want a direct match only of course).

Say the user stores www.facebook.com, this should match both http://www.facebook.com and https://www.facebook.com and it does

The problem is it is also matching sub-directories such as https://www.facebook.com/events/upcoming etc.

The regex for example:

/.+:\/\/www\.facebook\.com/

Matches the following:

https://www.facebook.com/events/upcoming

When it should just be matching

 http://www.facebook.com/
 https://www.facebook.com/

How can I fix this seemingly broken regex?


Solution

  • If you're being really specific about what you want to match, why not reflect that in your RegExp?

    /^https?:\/\/(?:(?:www|m)\.)?facebook\.com\/?$/
    

    Regular expression visualization

    • http or https
    • www., m. or no subdomain
    • facebook.com

    Demo

    edit to include optional trailing backslash