首页 > 文章列表 > 如何解析网页链接中的相对URL?

如何解析网页链接中的相对URL?

314 2025-03-18

如何解析网页链接中的相对URL?

解析href路径中的相对URL

当处理网页链接时,有时需要确定以相对路径指定的目标网址。以下是如何根据href路径判断最终URL网址:

例如,在以下网页中:

https://www.dataroma.com/m/holdings.php?m=BRK

包含如下表述:

<a href="/m/hist/hist.php?f=BRK&amp;s=AAPL" title="Holding/activity history">≡</a>

如何确定此链接的最终指向为何:

https://www.dataroma.com/m/hist/hist.php?f=BRK&amp;s=AAPL

利用相对源URL

根据MDN文档,上述链接被称为相对于源的URL。源是location.origin,在本例中为https://www.dataroma.com。

通过将相对路径与源URL结合,可以获得最终的URL:

最终URL = 源 + 相对路径

https://www.dataroma.com + /m/hist/hist.php?f=BRK&amp;s=AAPL
= https://www.dataroma.com/m/hist/hist.php?f=BRK&amp;s=AAPL

因此,该链接的最终指向为:

https://www.dataroma.com/m/hist/hist.php?f=BRK&amp;s=AAPL
来源:1731280658