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

5

我需要在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"…}

我需要的是 my-cat/my-title/,可以通过以下方式得到:


我不确定你的问题,因为location.pathname返回一个字符串,而不是一个对象。console.log(location.pathname.substr(1))应该适用于你。 - Rory McCrossan
1
@Solo不管你之前尝试了什么,你的方法是错误的。.pathname始终是一个字符串。 - Alnitak
@Solo 这不是一个答案。如果那解决了问题,那么这个问题可能应该被删除或关闭,因为问题是由语法或排版问题引起的。 - Rory McCrossan
2个回答

9

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

您也可以尝试:

String(window.location.pathname)

这是显式转换为字符串。

window.location.href还可以帮助您检索完整的URL。


0
使用toString()方法将您的对象转换为字符串。
示例:
var currentLocation = location.toString();

console.log(currentLocation);

o/p - "http://stackoverflow.com/posts/33895647/edit"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接