fix: Issue with Parameters Passed in the URL(#2124) (#2139)

* fix: Issue with Parameters Passed in the URL(#2124)

The '=' should be allowed within query parameter value. While first equals sign separates parameter name from its value, any subsequent occurrences are valid and should not be discarded.
The '#' in URL always indicates the start of URI Fragment component, and should not be treated as part of any parameter value.

* chore: gracefully fail when URLSearchParams throws error

---------

Co-authored-by: Anoop M D <anoop.md1421@gmail.com>
This commit is contained in:
Mateusz Pietryga 2024-08-29 09:16:20 +02:00 committed by GitHub
parent 36ef38be6a
commit 93080de2a8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 26 additions and 8 deletions

View File

@ -18,16 +18,17 @@ const hasLength = (str) => {
};
export const parseQueryParams = (query) => {
if (!query || !query.length) {
try {
if (!query || !query.length) {
return [];
}
return Array.from(new URLSearchParams(query.split('#')[0]).entries())
.map(([name, value]) => ({ name, value }));
} catch (error) {
console.error('Error parsing query params:', error);
return [];
}
let params = query.split('&').map((param) => {
let [name, value = ''] = param.split('=');
return { name, value };
});
return filter(params, (p) => hasLength(p.name));
};
export const parsePathParams = (url) => {

View File

@ -49,6 +49,23 @@ describe('Url Utils - parseQueryParams', () => {
{ name: 'b', value: '2' }
]);
});
it('should parse query with "=" character - case 9', () => {
const params = parseQueryParams('a=1&b={color=red,size=large}&c=3');
expect(params).toEqual([
{ name: 'a', value: '1' },
{ name: 'b', value: '{color=red,size=large}' },
{ name: 'c', value: '3' }
]);
});
it('should parse query with fragment - case 10', () => {
const params = parseQueryParams('a=1&b=2#I-AM-FRAGMENT');
expect(params).toEqual([
{ name: 'a', value: '1' },
{ name: 'b', value: '2' }
]);
});
});
describe('Url Utils - parsePathParams', () => {