17337: Added custom encode functions with tests
[arvados-workbench2.git] / src / common / url.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 export function getUrlParameter(search: string, name: string) {
6     const safeName = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
7     const regex = new RegExp('[\\?&]' + safeName + '=([^&#]*)');
8     const results = regex.exec(search);
9     return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
10 }
11
12 export function normalizeURLPath(url: string) {
13     const u = new URL(url);
14     u.pathname = u.pathname.replace(/\/\//, '/');
15     if (u.pathname[u.pathname.length - 1] === '/') {
16         u.pathname = u.pathname.substr(0, u.pathname.length - 1);
17     }
18     return u.toString();
19 }
20
21 export const customEncodeURI = (path: string) => {
22     return encodeURIComponent(path.replace(/%2F/g, '/'));
23 };
24
25 export const customDecodeURI = (path: string) => {
26     return decodeURIComponent(path.replace(/\//g, '%2F'));
27 };
28
29 export const encodeHash = (path: string) => {
30     return path.replace(/#/g, '%23');
31 };