Capture and Remove URL segment in custom JS – GTM

I need a custom JS variable for GTM that excludes everything from “/p/” until the end or the next “/”, what happens first.

The url after the /p/ can be anything, any length, and have nothing afterwards.

Before:

  • hostname/category/brand/some-snicker-model/p/NIBQ5448001
  • hostname/campaign/some-snicker-model/p/AB434222/?device=type

After:

  • hostname/category/brand/some-snicker-model
  • hostname/campaign/some-snicker-model/?device=type