[英]JavaScript function to replace URL param not working as intended
我有一個替換分頁按鈕上的URL參數的功能。 如果我的URL
是https://example.com/
,結果將得到正確的URL
,但是如果我的URL
已經具有一些參數(如小提琴中的) ,則僅替換最后一個參數。 在這種情況下,我也如何獲得正確的URL
?
var sURL = "https://example.com/?&page=2&order=price&direction=ASC"; //var sURL = "https://example.com/"; function insertParam(no, ord, dir) { var page = "page"; var order = "order"; var direction = "direction"; page = encodeURI(page); order = encodeURI(order); direction = encodeURI(direction); no = encodeURI(no); ord = encodeURI(ord); dir = encodeURI(dir); var kvp = sURL.substr(1).split('&'); var i = kvp.length; var x; while (i--) { x = kvp[i].split('='); if (x[0] === page) { x[1] = no; kvp[i] = x.join('='); break; } if (x[0] === order) { x[1] = ord; kvp[i] = x.join('='); break; } if (x[0] === direction) { x[1] = dir; kvp[i] = x.join('='); break; } } if (i < 0) { kvp[kvp.length] = [page, no].join('='); kvp[kvp.length] = [order, ord].join('='); kvp[kvp.length] = [direction, dir].join('='); } sURL = kvp.join('&'); alert(sURL); } insertParam(3, 'my_id', 'DESC');
我認為您需要遵循另一種方法來滿足您的要求,希望它會對您有所幫助。
function insertParam(endpoint, no, ord, dir){
const sURL = endpoint + "?&page=" + no + "&order=" + ord + "&direction=" + dir;
return sURL
}
const url = insertParam("https://example.com/", 2, 123, "ASC");
// https://example.com/?&page=2&order=123&direction=ASC
查看網址類。 它可以幫助您處理所有與URL相關的怪異事物。 這是您使用它的功能:
var sURL = "https://example.com/?&page=2&order=price&direction=ASC"; function insertParam(page = 2, order = "price", direction = "ASC") { const u = new URL(sURL); u.searchParams.set("page", page); u.searchParams.set("order", order); u.searchParams.set("direction", direction); return u.toString(); } console.log(insertParam(1, "foo", "DESC")); console.log(insertParam(5));
.as-console-wrapper{top:0;max-height:100%!important}
或更通用的解決方案
const urlBuilder = (url, defaults = {}) => (props) => { const u = new URL(url); for(let [key, value] of Object.entries(props ? { ...defaults, ...props } : defaults)) { u.searchParams.set(key, value); } return u.toString(); } // create a function that will build the urls for a particular page/route const routeFoo = urlBuilder("https://example.com", { page: 2, order: "price", direction: "ASC" }); console.log(routeFoo({ page: 5 })); console.log(routeFoo({ page: 1, direction: "DESC", foo: 42, additional: "properties", "also deals with weird/malicious stuff": "like special chars like /#%? & more" })); // or just the defaults console.log(routeFoo());
.as-console-wrapper{top:0;max-height:100%!important}
嘗試使用newurl = location.search.replace(/^.*?\\=/,``); newurl = newurl.replace(“ +”,“”);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.