我正在撰寫一個函式來檢測當前 URL 是否包含某個子字串。如果它包含,那么我想洗掉它。
例如,
localhost/4000?ab=2&item=google
localhost/4000?ab=2&item=google123
localhost/4000?ab=2&item=google1233&haha=有幫助
我的想法在下面......但有點卡在這個程序中
function changeUrl(item) {
var currentUrl = window.location.href;
if(currentUrl.includes('&item=') ){
.....
.....
return currentUrl
}else return;
}
uj5u.com熱心網友回復:
我不會嘗試將它作為字串來操作。JavaSccript 有一個非常好的工具來操作 URL,你不妨使用它:
str = 'http://localhost/4000?ab=2&item=google1233&haha=helpful';
url = new URL(str);
url.searchParams.delete('item'); // Idempotent call
result = url.toString();
uj5u.com熱心網友回復:
在這種情況下,最好使用 URLSearchParams。 MDN 檔案
URLSearchParams 介面定義了使用 URL 查詢字串的實用方法。
var url = new URL('https://example.com?foo=1&bar=2');
var params = new URLSearchParams(url.search);
// you can see params by this way
for (let p of params) {
console.log(p);
}
// if you want to check if some params are exist
console.log(params.has('foo')); // true
// if you want to delete some params
console.log(params.toString());
params.delete('foo');
console.log(params.toString());
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/421912.html
標籤:
