如何将window.location.pathname从对象“转换”为字符串?

时间:2015-11-24 13:59:24

标签: javascript jquery pathname

我需要JS / jQuery中的路径名(www.my-site.com/this-part/and-this-part/etc / ),但我需要它作为字符串不是对象。

换句话说,我需要JS / jQuery中的$_SERVER['REQUEST_URI'];

我试过了:

var page_pathname = location.pathname;

var page_pathname = location.pathname + location.search;

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

console.log所有的一切:

1。 Object {error: Object}

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

我需要console.logmy-cat/my-title/

2 个答案:

答案 0 :(得分:5)

window.location.pathname已经是一个字符串。

您也可以尝试:

String(window.location.pathname)

这是显式转换为字符串。

window.location.href也可以帮助您检索完整的网址。

答案 1 :(得分:0)

使用toString()方法将对象转换为字符串

实施例

var currentLocation = location.toString();

console.log(currentLocation);

o/p - "http://stackoverflow.com/posts/33895647/edit"
相关问题