EN
JavaScript - get file path from URL
7 points
In this short article, we would like to show how to get a file path from URL in JavaScript.
Practical example:
xxxxxxxxxx
1
const ORIGIN_EXPRESSION = /^(?:[a-z]+:)?\/\/[^\/]+/i;
2
3
const findMatching = (expression, text) => {
4
expression.lastIndex = 0;
5
return expression.exec(text);
6
};
7
8
const getPath = (url) => {
9
const matching = findMatching(ORIGIN_EXPRESSION, url);
10
if (matching) {
11
const origin = matching[0];
12
return url.substring(origin.length);
13
}
14
return url;
15
};
16
17
18
// Usage example 1:
19
20
console.log(getPath('http://my-domain.com/path/to/file.txt')); // /path/to/file.txt
21
console.log(getPath('https://my-domain.com/path/to/file.txt')); // /path/to/file.txt
22
23
24
// Usage example 2:
25
26
const urls = [
27
// Only path:
28
'/project/readme.txt',
29
30
// Only domain:
31
'//my-domain.com/project/readme.txt', // non-standard but accepted by web browsers
32
'http://my-domain.com/project/readme.txt',
33
'https://my-domain.com/project/readme.txt',
34
35
// Domain + port:
36
'//my-domain.com:8080/project/readme.txt', // non-standard but accepted by web browsers
37
'http://my-domain.com:8080/project/readme.txt',
38
'https://my-domain.com:8080/project/readme.txt'
39
];
40
41
for (let i = 0; i < urls.length; ++i) {
42
console.log(getPath(urls[i]));
43
}
Note: the solution returns in the paths
?
and#
parts too (search and hash parts).
This solution works only with URLs that are described in the standard (link here).
xxxxxxxxxx
1
const getPath = (url) => {
2
const instance = new URL(url);
3
return instance.pathname;
4
};
5
6
7
// Usage example:
8
9
console.log(getPath('http://my-domain.com/path/to/file.txt')); // /path/to/file.txt
10
console.log(getPath('https://my-domain.com/path/to/file.txt')); // /path/to/file.txt
11
12
console.log(getPath('https://my-domain.com:8080/path/to/file.txt')); // /path/to/file.txt
13
console.log(getPath('https://my-domain.com:8080/path/to/file.txt')); // /path/to/file.txt
Warning:
URL
class is supported major web browsers since 2014-2016.