使用JavaScript获取URL的部分

3

我目前在访问www.google.com/folder/folder/archive.php,并使用window.location来确定当前页面。实际上,我只想针对/archive.php进行操作,而不涉及其他内容。

有什么方法可以实现吗?

window.location.host = "www.google.com"

window.location.pathname = "folder/folder/archive.php"

???? = "/archive.php

你应该能够轻松地从路径名中提取出来... :) - techfoobar
只需使用:pathname.substr(pathname. lastIndexOf('/')) - Andrew
我目前在 www.google.com/folder/folder/archive.php。我怀疑这个。example.com是为了这个原因而保留的 :) - Gareth
可能是如何在JavaScript中提取URL的文件名?的重复问题。 - Felix Kling
哦 Gareth!我下次会记住的。 :) - user1469270
5个回答

6
尝试这个 :)
console.log(window.location.href.split('/').pop())

我也在考虑这个问题,但如果我的URL是这样的:example.com/http://google.com/otherPage.js,我该如何将不同的部分拆分出来? - B''H Bi'ezras -- Boruch Hashem
甚至 example.com/index.php?page=http://google.com - B''H Bi'ezras -- Boruch Hashem

4
您需要分割数组并获取最后一部分。可以像这样做:
var a = window.location.pathname.split("/");
console.log(a[a.length - 1]);

谢谢。如果我只是执行 console.log(a[-1]);,为什么控制台会显示 undefined - user1469270
@Prateek:我的解决方案与URL的大小无关。目标是实现URL的最后一部分。 - Uncle Aaroh

0

试试这个

var path = "www.google.com/folder/folder/archive.php";
console.log(path.substring(path.lastIndexOf('/')+1));

0

这将从最后一个'/'选择部分。

var last =

window.location.toString().substr(window.location.toString().lastIndexOf('/'));

无论在哪个页面运行此脚本,最后的路径始终是相同的。

例如:http://www.example.com/../../../../../test.html

输出将为 test.html

http:// - Protocol
www - Server-Name (subdomain)
example - Second Level Domain (SLD)
com - Top Level Domain (TLD)
/test.html - Path

0
alert("/"+window.location.pathname.split("/")[2] );

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