Languages
[Edit]
EN

JavaScript - get file path from URL

7 points
Created by:
Nathanial-Donald
584

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: URL class is supported major web browsers since 2014-2016.

 

See also

  1. JavaScript - get file name from path or URL (works in Web Browser)

References

  1. URL - Wikipedia
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join