Skip to content

Commit dc9ed19

Browse files
jvartanianJustin Vartanian
andauthored
Parse URL params properly (#183)
Co-authored-by: Justin Vartanian <[email protected]>
1 parent 1114614 commit dc9ed19

File tree

2 files changed

+9
-18
lines changed

2 files changed

+9
-18
lines changed

src/web-utils.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ describe("Url param extraction", () => {
191191
const foo = WebUtils.randomString();
192192
const paramObj = WebUtils.getUrlParams(`https://app.example.com?random=${random}&foo=${foo}#ignored`);
193193
expect(paramObj!["random"]).toStrictEqual(random);
194-
expect(paramObj!["foo"]).toStrictEqual(`${foo}#ignored`);
194+
expect(paramObj!["foo"]).toStrictEqual(`${foo}`);
195195
});
196196

197197
it('should use hash flag and ignore query flag', () => {

src/web-utils.ts

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -60,33 +60,24 @@ export class WebUtils {
6060
* Public only for testing
6161
*/
6262
static getUrlParams(url: string): { [x: string]: string; } | undefined {
63-
const urlString = `${url}`.trim();
63+
const urlString = `${url ?? ''}`.trim();
6464

6565
if (urlString.length === 0) {
6666
return;
6767
}
6868

69-
// #132
70-
let hashIndex = urlString.indexOf("#");
71-
let queryIndex = urlString.indexOf("?");
72-
73-
if (hashIndex === -1 && queryIndex === -1) {
69+
const parsedUrl = new URL(urlString);
70+
if (!parsedUrl.search && !parsedUrl.hash) {
7471
return;
7572
}
76-
let paramsIndex: number;
77-
if (hashIndex > -1 && queryIndex === -1) {
78-
paramsIndex = hashIndex;
79-
} else if (queryIndex > -1 && hashIndex === -1) {
80-
paramsIndex = queryIndex;
81-
} else {
82-
paramsIndex = hashIndex > -1 && hashIndex < queryIndex ? hashIndex : queryIndex;
83-
}
8473

85-
if (urlString.length <= paramsIndex + 1) {
86-
return;
74+
let urlParamStr;
75+
if (parsedUrl.search) {
76+
urlParamStr = parsedUrl.search.substr(1);
77+
} else {
78+
urlParamStr = parsedUrl.hash.substr(1);
8779
}
8880

89-
const urlParamStr = urlString.slice(paramsIndex + 1);
9081
const keyValuePairs: string[] = urlParamStr.split(`&`);
9182
// @ts-ignore
9283
return keyValuePairs.reduce((accumulator, currentValue) => {

0 commit comments

Comments
 (0)