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:
// ONLINE-RUNNER:browser;
const ORIGIN_EXPRESSION = /^(?:[a-z]+:)?\/\/[^\/]+/i;
const findMatching = (expression, text) => {
expression.lastIndex = 0;
return expression.exec(text);
};
const getPath = (url) => {
const matching = findMatching(ORIGIN_EXPRESSION, url);
if (matching) {
const origin = matching[0];
return url.substring(origin.length);
}
return url;
};
// Usage example 1:
console.log(getPath('http://my-domain.com/path/to/file.txt')); // /path/to/file.txt
console.log(getPath('https://my-domain.com/path/to/file.txt')); // /path/to/file.txt
// Usage example 2:
const urls = [
// Only path:
'/project/readme.txt',
// Only domain:
'//my-domain.com/project/readme.txt', // non-standard but accepted by web browsers
'http://my-domain.com/project/readme.txt',
'https://my-domain.com/project/readme.txt',
// Domain + port:
'//my-domain.com:8080/project/readme.txt', // non-standard but accepted by web browsers
'http://my-domain.com:8080/project/readme.txt',
'https://my-domain.com:8080/project/readme.txt'
];
for (let i = 0; i < urls.length; ++i) {
console.log(getPath(urls[i]));
}
Note: the solution returns in the paths
?and#parts too (search and hash parts).
Alternative solution
This solution works only with URLs that are described in the standard (link here).
// ONLINE-RUNNER:browser;
const getPath = (url) => {
const instance = new URL(url);
return instance.pathname;
};
// Usage example:
console.log(getPath('http://my-domain.com/path/to/file.txt')); // /path/to/file.txt
console.log(getPath('https://my-domain.com/path/to/file.txt')); // /path/to/file.txt
console.log(getPath('https://my-domain.com:8080/path/to/file.txt')); // /path/to/file.txt
console.log(getPath('https://my-domain.com:8080/path/to/file.txt')); // /path/to/file.txt
Warning:
URLclass is supported major web browsers since 2014-2016.