Search code examples
javascriptjquerypathname

How to "convert" window.location.pathname from object to string?


I need pathname (www.my-site.com/this-part/and-this-part/etc/) in JS/jQuery but I need it as string not as object.

In other words I need $_SERVER['REQUEST_URI']; in JS/jQuery.

I've tried:

var page_pathname = location.pathname;

var page_pathname = location.pathname + location.search;

var page_pathname = (location.pathname+location.search).substr(1);

All I get with console.log:

1. Object {error: Object}

2. Location {hash: "", search: "", pathname: "/my-cat/my-title/", port: "", hostname: "www.my-site.com"…}

What I need with console.log: my-cat/my-title/


Solution

  • window.location.pathname is already a string.

    You can also try:

    String(window.location.pathname).

    This is explicit conversion to string.

    window.location.href will also help you in retrieving the full url.