Extract Previous Page Path from Referrer

The following can be used as a custom javascript macro to extract the last piece of the URL path from the referrer. I will typically use something like this code for form submission thank you pages to identify the previous page page and pass it to a label for GA event tracking.

function(){
var referrerPath= document.referrer.split('/');
var endPath = referrerPath[referrerPath.length-2];
if (document.referrer.split('/')[2]!=document.location.hostname)
  {
  return 'external';
  }
else if (referrerPath.length<=4)
  {
  return '/';
  }
else
{
return endPath;
}
}