首頁 > web前端 > js教程 > 主體

URL對象

Mary-Kate Olsen
發布: 2024-10-11 10:36:29
原創
279 人瀏覽過

The URL Object

概述

JavaScript 中的 URL 物件提供了一種輕鬆使用和操作 URL 的方法。當您需要在程式碼中建構、解析或修改 URL 時,它特別有用。

很多時候使用模板字串來在 JavaScript 中建立 URL。通常這很簡單且足夠清晰,但 URL 物件是處理 URL 的更強大的 OOP 方法。

甚至OpenWeatherMap.org 在文件中也使用模板字串:https://api.openweathermap.org/data/3.0/onecall?lat={lat}&lon={lon}&exclude={part}&appid= {API key }

對於相當靜態的 URL,這很好,但是如果您想對此 URL 進行更改,您可能需要考慮使用 URL 物件。

// Using template strings
const lat = 32.087;
const lon = 34.801;
const apiKey = 'your_api_key';
const url = `https://api.openweathermap.org/data/3.0/onecall?lat=${lat}&lon=${lon}&appid=${apiKey}`;

// Using the URL object
const openWeatherUrl = new URL('https://api.openweathermap.org/data/3.0/onecall');
openWeatherUrl.searchParams.set('lat', lat);
openWeatherUrl.searchParams.set('lon', lon);
openWeatherUrl.searchParams.set('appid', apiKey);
登入後複製

基本用法

您可以透過將 URL 字串傳遞給其建構函式來建立新的 URL 物件。

在這種情況下(與上面相反),整個 URL 與各個部分一起傳入:

const url = new URL('https://example.com:8080/path?query=123#section');
登入後複製

特性

URL 物件有幾個屬性,您可以使用它們來存取 URL 的部分內容:

  • href:字串形式的完整 URL。
  • 協議:協議(例如 https:)。
  • 主機名稱:網域名稱(例如 example.com)。
  • port:連接埠號(例如 8080)。
  • 路徑名:網域名稱後面的路徑(例如/path)。
  • search:查詢字串,包括? (例如?query=123)。
  • hash:片段標識符,包括#(例如#section)。
  • 主機:主機名稱和連接埠組合(例如 example.com:8080)。
  • origin:URL 的來源,即協定、主機名稱和連接埠。
> const url = new URL('https://example.com:8080/path?query=123#section');
> url.port
'8080'
> url.protocol
'https:'
> url.hostname
'example.com'
> url.pathname
'/path'
> url.search
'?query=123'
> url.hash
'#section'
> url.host
'example.com:8080'
登入後複製

這些也可以用來更改 URL 的不同部分? :

> url.port = 1234
1234
> url.pathname = "differentpath"
'differentpath'
> url.hostname = "example.org"
'example.org'
> url
URL {
  href: 'https://example.org:1234/differentpath?query=123#section',
  origin: 'https://example.org:1234',
  protocol: 'https:',
  username: '',
  password: '',
  host: 'example.org:1234',
  hostname: 'example.org',
  port: '1234',
  pathname: '/differentpath',
  search: '?query=123',
  searchParams: URLSearchParams { 'query' => '123' },
  hash: '#section'
}
登入後複製

方法

URL 物件也具有一些方法來幫助修改 URL 並與 URL 互動。

例如,URL 搜尋參數 是一個鍵值對,用於通知 API 伺服器詳細資訊以服務使用者。

url.searchParams:傳回一個 URLSearchParams 對象,該對象提供使用查詢字串參數的方法。您可以:

取得查詢參數:url.searchParams.get('query')
設定查詢參數: url.searchParams.set('query', '456')
刪除查詢參數: url.searchParams.delete('query')

迭代查詢參數:

url.searchParams.forEach((value, key) => {
  console.log(key, value);
});
登入後複製

toString():以字串形式傳回完整 URL,反映對屬性或查詢參數所做的任何變更。

開放天氣圖 API 範例

以下是 OpenWeatherMap 的文檔:https://openweathermap.org/api/one-call-3

這是一個簡單的範例,展示如何建立 URL 物件並操作其各個部分:

// get values to interpolate to URL
const apiKey = process.env.openWeatherApiKey || 0
const [lat, lon] = [32.08721095615897, 34.801588162316506]

const openWeatherUrl = new URL("https://api.openweathermap.org")

openWeatherUrl.pathname = "data/3.0/onecall"
openWeatherUrl.searchParams.set('lat',lat)
openWeatherUrl.searchParams.set('lon',lon)

// from the docs
openWeatherUrl.searchParams.set('exclude', 'hourly')

openWeatherUrl.searchParams.set('appid', apiKey)

console.log(openWeatherUrl)
登入後複製

輸出:

URL {
  href: 'https://api.openweathermap.org/data/3.0/onecall?lat=32.08721095615897&lon=34.801588162316506&exclude=hourly&appid=0',
  origin: 'https://api.openweathermap.org',
  protocol: 'https:',
  username: '',
  password: '',
  host: 'api.openweathermap.org',
  hostname: 'api.openweathermap.org',
  port: '',
  pathname: '/data/3.0/onecall',
  search: '?lat=32.08721095615897&lon=34.801588162316506&exclude=hourly&appid=0',
  searchParams: URLSearchParams {
    'lat' => '32.08721095615897',
    'lon' => '34.801588162316506',
    'exclude' => 'hourly',
    'appid' => '0' },
  hash: ''
}
登入後複製

概括

JavaScript 中的 URL 物件提供了一種處理 URL 的結構化方法,允許輕鬆操作和建立複雜的 URL。雖然模板字串對於靜態 URL 來說簡單且有效,但 URL 物件對於 URL 是動態的或需要頻繁修改的情況來說是理想的選擇。


照片由 Anne Nygård 在 Unsplash 上拍攝

以上是URL對象的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!