如何使用 JavaScript 編碼 URL

如果您需要將 URL 作為 GET 請求的一部分發送,那麼您可能需要將其編碼。 在 JavaScript 中,該如何編碼 URL? 根據您的需求,有兩個 JavaScript 函數可以幫助您。 第一個是 encodeURI(),第二個是 encodeURIComponent()。 注意:您可能會讀到 escape() 的相關資訊,但它已被棄用,不應使用。 這兩種方法在編碼哪些字符方面有所不同。 具體來說,encodeURI() 不會編碼 ~!@#$&*()=:/,;?+,而 encodeURIComponent() 則不會編碼 -_.!~*'(),而編碼其他所有字符。它們之間的區別是為了不同的用途: encodeURI() 用於編碼完整的 URL。 encodeURIComponent() 用於編碼單個 URL 參數值。 如果要對完整的 URL 調用 encodeURIComponent(),因為它會編碼 /,URL 路徑分隔符也將被編碼(以及其他內容): encodeURI("http://example.com/ hey!/") //"http://example.com/%20hey!/" encodeURIComponent("http://www.example.org/a file with spaces.html") //"http%3A%2F%2Fexample.com%2F%20hey!%2F" MDN 提出了一個改進方案,以符合 RFC 3986 標準,使用以下函數實現: const fixedEncodeURIComponent = (str) => { return encodeURIComponent(str).replace(/[!'()\*]/g, (c) => { return '%' + c.charCodeAt(0).toString(16) }) } 您可以將它應用於要添加到 URL 中的每個參數。...