Search code examples
javascriptregexreferrer

Yet Another document.referrer.pathname Thing


I'm looking for the equivalent of "document.referrer.pathname". I know there are other questions that are similar to this on SO, but none of them handle all the use cases. For example:

http://example.com/RESULT

http://example.com/RESULT/

http://example.com/RESULT?query=string

All examples should return:

RESULT

or

https://example.com/EXTENDED/RESULT/

EXTENDED/RESULT

Some folks may want the trailing slash included, but I don't because I'm matching against a list of referrers.

I've started with:

document.referrer.match(/:\/\/.*\/(.*)/)[1]

and am struggling adding the query string parsing.

Thanks!


Solution

  • Try this regular expression:

    .match(/\/\/.*?\/(.*?)\/?(\?.*)?$/)[1]
    

    DEMO