【问题标题】:How to "convert" window.location.pathname from object to string?如何将 window.location.pathname 从对象“转换”为字符串?
【发布时间】:2016-02-27 00:12:53
【问题描述】:

我需要 JS/jQuery 中的路径名 (www.my-site.com/this-part/and-this-part/etc/) 但我需要它作为 string强>不作为对象。

换句话说,我在 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.log 我需要什么:my-cat/my-title/

【问题讨论】:

  • 我不确定您的问题,因为location.pathname 返回一个字符串,而不是对象console.log(location.pathname.substr(1)) 应该适合您。
  • @Solo 无论你在尝试什么,你都尝试错了。 .pathname总是是一个字符串。
  • @Solo 这不是答案。如果这解决了问题,那么这个问题可能应该被删除或关闭,因为问题是由于语法或印刷问题造成的。

标签: javascript jquery pathname


【解决方案1】:

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

你也可以试试:

String(window.location.pathname)

这是到字符串的显式转换。

window.location.href 还将帮助您检索完整的网址。

【讨论】:

    【解决方案2】:

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

    例子

    var currentLocation = location.toString();
    
    console.log(currentLocation);
    
    o/p - "http://stackoverflow.com/posts/33895647/edit"
    

    【讨论】:

      猜你喜欢
      • 2021-02-03
      • 2018-07-19
      • 2019-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多