Search code examples
javascriptsalesforce-lightning

URL Parameter Separation


How to use 'searchParams' so as to get multiple URL parameters separated by '&' , which also contain '&' in parameter string.

For e.g. I have a URL : https:*******.com?selectedCategory=Cash%2CCheques+%26+Misc%26transactionType%3dDebit

Using the below code :

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, Cheques & Misc


Solution

  • If you want to keep the URL the same, you could decode the transaction type, after you access the category parameter. I used a look-behind regular expression to split on '&' characters preceded by a non-space. After I have my tokens, I can shift the "head" off of the resulting list and then transform the rest of the tokens into an object.

    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


    Notes

    Your URL does appear wrong, since you encoded the '&' separator as "%26" right before "transaction". Also, the '=' was encoded as "%3d" following "transaction".

    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

    This is with the altered 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