Get file name from an URL in Javascript

Get file name from an URL in Javascript

Example with an URL like this:
 const url = 'http://4codev.com/example-file.jpg?anyparam=xyz';
 //or from browser: const url = window.location.pathname;


Get file name included params from URL:

 const fileNameParams = url.substring(url.lastIndexOf('/') + 1);
 
 console.log(fileNameParams)
 // result: example-file.jpg?anyparam=xyz


The substring method extracts the characters from a string, arguments: start and end position, and returns the new sub string
The lastIndexOf method returns the index within the calling String object of the last occurrence of the specified value


Get file name without params:

 const fileNameParams = url.substring(url.lastIndexOf('/') + 1);
 const filename = fileNameParams.substring(0, fileNameParams.indexOf('?'));
 
 console.log(filename)
 // result: example-file.jpg



Create a helper to reuse:

 function getFileName(url, includeParams) {
      const filename = url.substring(url.lastIndexOf('/') + 1)
      if (!includeParams) return filename.substring(0, filename.indexOf('?'))
      return filename
 }
 
 console.log(getFileName(url, true))
 // result: example-file.jpg?anyparam=xyz
 
 console.log(getFileName(url, false))
 // result: example-file.jpg


© 2019 4codev

Created with love by Sil.