有沒有一種方法可以使用 HTML css 和 JavaScript 在前 10 個字符后找到網頁的 URL。例如,如果 URL 是 random.com/abc,程式將只獲取 URl 的 /abc 部分并將其記錄在控制臺中。如何才能做到這一點?
uj5u.com熱心網友回復:
您需要從視窗位置物件獲取路徑名。
window.location.pathname
uj5u.com熱心網友回復:
您可以使用window.location.hrefwithsubstring()來選擇特定索引后的一系列字符或字符。
window.location.href.substring(10);
uj5u.com熱心網友回復:
是的,您可以使用window.location.href完成此操作。
示例輸出:
window.location.href: 'https://stackoverflow.com/questions/69409934/javascript-get-portion-of-a-page-url'
您現在可以拆分此字串,并獲得所需的部分:
window.location.href.split('/')
輸出:
0: "https:"
1: ""
2: "stackoverflow.com"
3: "questions"
4: "69409934"
5: "javascript-get-portion-of-a-page-url"
length: 6
現在將其登錄到控制臺:
console.log(window.location.href.split('/')[3])
你的結果:
'questions'
uj5u.com熱心網友回復:
要獲取路徑,請使用 pathName。
console.log(window.location.pathname);
console.log((new URL('http://www.example.com/abc/123')).pathname);
沒有理由拆分和使用索引。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/318230.html
標籤:javascript html 网址 安慰
上一篇:gov.uk是頂級域名還是域名?
