我有一個類似於https://app.ticketmaster.com/discovery/v2/events?apikey=xxxxxx&keyword=Sarah%20Jarosz&latlong=xx.xxxxx,-xxx.xxxx&radius=15&unit=miles&locale= *的鏈接,它作為我的函數中的參數。我想獲取此鏈接的關鍵字部分的值,並且希望找到比使用子字符串編寫自己的函數更容易的方法。
我熟悉獲取鏈接部分的 window.locaiton.____ 方法,但這在函數中作為參數傳遞,因此我無法使用該方法。我嘗試使用此問題中定義的方法Parse an URL in JavaScript但我不能使用 .keyword 而不是 .search 來僅獲取關鍵字部分。
使用 URL 和 URLSearchParams api
const urlString =' https://app.ticketmaster.com/discovery/v2/events?apikey=xxxxxx&keyword=Sarah%20Jarosz&latlong=xx.xxxxx,-xxx.xxxx&radius=15&unit=miles&locale='
function getKeyword (str) {
const url = new URL(str);
return url.searchParams.get('keyword');
}
console.log(getKeyword(urlString))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句