URL参数分离

URL Parameter Separation

如何使用'searchParams'得到多个由'&'分隔的URL参数,参数字符串中也包含'&'

例如我有一个 URL : https:*******.com?selectedCategory=Cash%2CCheques+%26+Misc%26transactionType%3dDebit

使用下面的代码:

let pageURL = new URL(decodeURIComponent(document.URL));
const urlParams = pageURL.searchParams;
let selectedCategoryName = urlParams.get('selectedCategory');
let categoryTransType = urlParams.get('transactionType');
console.log(selectedCategoryName);
console.log(categoryTransType);

selectedCategoryName returns Cash,Cheques instead of Cash, Checks & Misc

如果您想保持 URL 不变,您可以在访问类别参数后解码交易类型。我使用 look-behind 正则表达式拆分 '&' 个字符,前面是 non-space。获得标记后,我可以将结果列表中的“头部”移开,然后将其余标记转换为一个对象。

const url = new URL('https://google.com?selectedCategory=Cash%2CCheques+%26+Misc%26transactionType%3dDebit');
const selectedCategory = url.searchParams.get('selectedCategory');

const tokens = selectedCategory.split(/(?<=\S)&/g);
const head = tokens.shift();
const rest = Object.fromEntries(tokens.map(pair => pair.split('=')));

console.log(head); // Cash,Cheques & Misc
console.log(rest.transactionType); // Debit


备注

您的 URL 确实出现错误,因为您在 "transaction" 之前将 '&' 分隔符编码为 "%26"。此外,'='"transaction".

之后被编码为 "%3d"

const url = new URL('https://google.com?selectedCategory=Cash%2CCheques+%26+Misc%26transactionType%3dDebit');
const selectedCategory = url.searchParams.get('selectedCategory');
console.log(selectedCategory); // Cash,Cheques & Misc&transactionType=Debit

这是修改后的 URL:

const url = new URL('https://google.com?selectedCategory=Cash%2CCheques+%26+Misc&transactionType=Debit');
const selectedCategory = url.searchParams.get('selectedCategory');
const transactionType = url.searchParams.get('transactionType');
console.log(selectedCategory); // Cash,Cheques & Misc
console.log(transactionType); // Debit