如何从 JavaScript 中的 url 获取路径名值?

How can I get pathname values from url in JavaScript?

我有这个:

http://example.com/iu4pa9rm8vfh.html?param_1

我想要这个:

iu4pa9rm8vfh
var url ="http://example.com/iu4pa9rm8vfh.html?param_1";
  document.getElementById("demo").innerHTML = 
"The pathname of this page is :" + url.pathname;

在此先感谢您的指导!

更新结果有什么问题

<!DOCTYPE html>
<html>

<body>

  <p id="demo"></p>

  <script>
    const url = new URL("http://example.com/iu4pa9rm8vfh.html?param_1")
    const pathname = url.pathname.match(/([0-9a-z]+)/)
    console.log(pathname[0])

    document.getElementById("demo").innerHTML = "The pathname of this page is :" + pathname;
  </script>

</body>

</html>

您可以使用 URL 构造函数构建一个 URL 对象,如下所示:

const url = new URL("http://example.com/iu4pa9rm8vfh.html?param_1")
console.log(url.pathname)

然后去掉你不想要的部分。或者更确切地说,在下面的示例中,对路径名执行正则表达式以仅检索字母数字字符:

const url = new URL("http://example.com/iu4pa9rm8vfh.html?param_1")
const pathname = url.pathname.match(/([0-9a-z]+)/)
console.log(pathname[0])

请注意,如果您向 URL 构造函数提供无效的 URL,那么它将抛出一个错误,因此请确保您捕获并妥善处理它。

关于 URL 的更多信息:


当您用 tag (perhaps you require an answer that works in <=IE11 as these browsers do not support the URL constructor) 标记这个问题时,您可以使用以下方法:

function parseUrl(url) {
    var a = document.createElement('a');
    a.href = url;
    return a;
}

const url = parseUrl('http://example.com/iu4pa9rm8vfh.html?param_1')
const pathname = url.pathname.match(/([0-9a-z]+)/)
console.log(pathname[0])

(修改自 this answer。)

你可以这样做:

const url = new URL('http://example.com/iu4pa9rm8vfh.html?param_1')
let path = url.pathname.split('.')[0].replace('/','')
document.getElementById("demo").innerHTML = "The pathname of this page is :" + path;

<!DOCTYPE html>
<html>

<body>

  <p id="demo"></p>

  <script>
    const url = new URL('http://example.com/iu4pa9rm8vfh.html?param_1')
    let path = url.pathname.split('.')[0].replace('/','')
    document.getElementById("demo").innerHTML = "The pathname of this page is :" + path;
  </script>

</body>

</html>

您可以通过多种不同的方式完成此操作,但我建议您使用 subString(startIndex,endIndex)

以下代码将 return .com/.html

之间的任何内容

var url = "http://example.com/iu4pa9rm8vfh.html?param_1";

url.substring(url.indexOf('.com/')+5,url.indexOf('.html'));

您可以通过多种方式获取路径名。

但从技术上讲,您应该使用 URL 构造函数方法从 URL 中创建一个对象。然后使用其 属性 获取路径名。

属性 名称:路径名

const url = new URL("http://example.com/iu4pa9rm8vfh.html?param_1")
console.log(url.pathname.replace("/", "").replace(".html",""))

我已经使用替换方法删除了路径名中的斜杠和 .html 标记。 我希望它有所帮助! :)

尽可能使用JavascriptURLApi:https://developer.mozilla.org/en-US/docs/Web/API/URL_API

let addr = new URL("http://example.com/iu4pa9rm8vfh.html?param_1");
// addr.pathname will return "/iu4pa9rm8vfh.html"
// Many wasys to skin this cat, but below is one way using split and slice
// Result will be "iu4pa9rm8vfh"
console.log(addr.pathname.split('.')[0].slice(1));