JAVASCRIPT - GET PORTION OF URL PATH

Royce Roy

Total Post:149

Points:1043
Posted by  Royce Roy
 1780  View(s)
Ratings:
Rate this:

Hi Everyone!

What is the correct way to pull out just the path from a URL using JavaScript?

Example:
I have URL
http://www.somedomain.com/account/search?filter=a#top
but I would just like to get this portion
/account/search

I am using jQuery if there is anything there that can be leveraged.

Thanks in advance

  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: JavaScript - Get Portion of URL Path

    Hi Royce!

    There is a property of the built-in window.location object that will provide that.

    // If URL is http://www.somedomain.com/account/search?filter=a#top

    window.location.pathname // /account/search

    // For reference:

    window.location.host     // www.somedomain.com (includes port if there is one)
    window.location.hostname // www.somedomain.com
    window.location.hash     // #top
    window.location.href     // http://www.somedomain.com/account/search?filter=a#top
    window.location.port     // (empty string)
    window.location.protocol // http:
    window.location.search   // ?filter=a

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!