5

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/

Solo
  • 6,687
  • 7
  • 35
  • 67
  • I'm unsure of your issue, as `location.pathname` returns a string, not an object`console.log(location.pathname.substr(1))` should work for you. – Rory McCrossan Nov 24 '15 at 14:03
  • 1
    @Solo whatever you were trying, you were trying it wrong. `.pathname` is _always_ a string. – Alnitak Nov 24 '15 at 14:14
  • @Solo it's not an answer. If that solved the problem then this question should probably be deleted or closed as the issue was due to a syntax or typographical issue. – Rory McCrossan Nov 24 '15 at 14:16

2 Answers2

9

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.

Charlie
  • 22,886
  • 11
  • 59
  • 90
0

Use to toString() method to transform your object to string

Example

var currentLocation = location.toString();

console.log(currentLocation);

o/p - "http://stackoverflow.com/posts/33895647/edit"
Kaushik
  • 2,072
  • 1
  • 23
  • 31
koninos
  • 4,969
  • 5
  • 28
  • 47