Languages
[Edit]
EN

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

6 points
Created by:
Zoya-Gaines
653

In this short article, we would like to show how to get a filename from path or URL in JavaScript under a web browser.

Practical example:

// ONLINE-RUNNER:browser;

const SEPARATOR_EXPRESSION = /([^\\\/¥₩]+)$/i;

const findMatching = (expression, text) => {
    expression.lastIndex = 0;
    return expression.exec(text);
};

const getFileName = (fileLocation) => {
    const matching = findMatching(SEPARATOR_EXPRESSION, fileLocation);
    if (matching) {
        return matching[0];
    }
    return null;
};


// Usage example 1:

console.log(getFileName('/path/to/file.txt'));                      // file.txt
console.log(getFileName('C:\\path\\to\\file.txt'));                 // file.txt
console.log(getFileName('http://my-domain.com/path/to/file.txt'));  // file.txt


// Usage example 2:

const items = [
  // Files:
    'readme.txt',

  // Paths:
    'project/readme.txt',
    'project\\readme.txt',
    '/project/readme.txt',
    'C:\\project\\readme.txt',

  // WWW:
    'http://my-domain.com/project/readme.txt',
    'https://my-domain.com/project/readme.txt',

  // FTP / SFTP:
    'ftp://my-domain.com/project/readme.txt',
    'sftp://my-domain.com/project/readme.txt',

  // Japanese and Korean:
    'C:¥project¥readme.txt', 
    'C:₩project₩readme.txt'
];

for (let i = 0; i < items.length; ++i) {
	console.log(getFileName(items[i]));  // readme.txt
}

Note: ¥ and are used because of possible Japanese and Korean paths separators.

 

See also

  1. JavaScript - get file path from URL

References

  1. The history of the path separator in Japanese and Korean Windows - Microsoft DevBlogs

Alternative titles

  1. JavaScript - get filename from path or URL (works in Web Browser)
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