Languages
[Edit]
EN

JavaScript - get file name from path or url in Web Browser

6 points
Created by:
Zoya-Gaines
293

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

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.

References

  1. The history of the path separator in Japanese and Korean Windows - The Old New Thing
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