-
-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathtest-encode.js
More file actions
32 lines (27 loc) · 1.11 KB
/
test-encode.js
File metadata and controls
32 lines (27 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function removeInitialAndTrailingSlashes(input) {
return input.replace(/^\/+|\/+$/g, '');
}
function encodePath(input) {
const cleanInput = removeInitialAndTrailingSlashes(input);
const [pathPart, rest] = cleanInput.split("?", 2);
let encodedPath = encodeURIComponent(pathPart).replaceAll("%2F", "/");
let result = encodedPath;
if (rest !== undefined) {
const [searchPart, hashPart] = rest.split("#", 2);
result += `?${searchPart}`;
if (hashPart !== undefined) {
result += `#${hashPart}`;
}
} else {
const [pathOnly, hashOnly] = cleanInput.split("#", 2);
if (hashOnly !== undefined) {
encodedPath = encodeURIComponent(pathOnly).replaceAll("%2F", "/");
result = `${encodedPath}#${hashOnly}`;
}
}
return result;
}
console.log(encodePath("products/B00BZQPQLQ?category_op=%3D%3D&category_value=babys#side"));
console.log(encodePath("products/B00BZQPQLQ#side"));
console.log(encodePath("products/B00BZQPQLQ"));
console.log(encodePath("/products/B00BZQPQLQ/?category_op=%3D%3D&category_value=babys"));