在我繼續之前,請允許我說,我已經看了許多主題,但沒有找到一個適合我的答案。
基本上,我建立了一個自定義鏈接縮短器,我使用 URLSearchParams 從 URL 搜索查詢中提取要縮短的 URL 和自定義蛞蝓,如下所示:
var e = window.location.search;
const urlParams = new URLSearchParams(e)。
const url = urlParams.get("url")。
const slug = urlParams.get("slug") 。
其中查詢的格式是。?url=https://google.com&slug=customslug
在處理完引數后,URL字串被用trim()處理,以洗掉任何空白處。當我使用的API(https://short.io)被呼叫時,最終的輸出將用encodeURIComponent()進行編碼。
然而,我希望能夠用&來傳遞URL,就像這樣。? url=https://google.com/&testing&slug=customslug。我理想的解決方案是簡單地將不屬于&引數的任何&slug視為&url引數中包含的URL的一部分。目前,如果&字符沒有連接到一個有效的引數(url或slug),它將被忽略。
我曾嘗試使用encodeURIComponent()對查詢輸入進行編碼,但這將導致無法接收到任何定義的引數。我還嘗試使用 split("&slug",1) 來分割輸入,但這導致了一個陣列,而我無法將陣列傳遞給 Short.io API。
有什么建議嗎?
uj5u.com熱心網友回復:
你應該使用URL編碼的安培符號&。
var e = "? url=https://google.com/&testing&slug=customslug"。
const urlParams = new URLSearchParams(e)。
const url = urlParams.get("url")。
const slug = urlParams.get("slug") 。
console.log(url)。
console.log(slug);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
我通過借鑒@CherryDT關于使用window.location.hash來獲取我的URL字串的意見,解決了我的問題。最終,我選擇了放棄在地址欄中添加lug的想法,因為這將給我的腳本帶來更多的問題。
雖然這個解決方案只適用于我的目的,但我還是詳細介紹了這個解決方案,因為它可以作為解決無法對地址欄中傳遞的 URL 字串進行編碼這一問題的變通方法。也許對某人來說是有用的,總有一天。
。var e = window.location. href.replace(window。 location.hash, '')。)
if (e.endsWith("?") ==true) {
var url = window.location。 hash.substr(1)。
if (url == "") {
//錯誤代碼。
} else {
console.log("A URL to be shortened was provided via hash." )。
//將URL傳遞給腳本的其余部分。
}
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/319545.html
標籤:
上一篇:如何填寫陣列中的數值
下一篇:從Firebase存盤中獲取URL并將其設定為AVAudioPlayer時總是出現錯誤(swiftxcode)。
