Hướng dẫn file name javascript


This snippet will get the filename from the url. The filename is the last part of the URL from the last trailing slash. For example, if the URL is http://www.example.com/dir/file.html then file.html is the file name.

Explanation

var url = window.location.pathname;

This declares the url variable and adds the current pathname as its value.

var filename = url.substring(url.lastIndexOf('/')+1);
alert(filename);

substring (method) - extract characters from start (parameter). url is the stringObject url.substring(start)

lastIndexOf (method) - position of last occurrence of specified string value, in this case the ‘/’

Add one to lastIndexOf because we do not want to return the ‘/’

Full snippet

var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
alert(filename);

Because cases tend to fail with custom code, I looked up to the JavaScript URL class. Alas, it chokes on relative URLs! Also, it doesn't have a property to get the file name. Not epic.

There has to be a good library out there which solves this common problem. Behold URI.js. All you need is a simple statement like the following:

let file = new URI(url).filename()

Then we can create a simple function that does null checks and removes the file extension:

function fileName(url) {
   if (url === null || typeof url === 'undefined')
      return ''
   let file = new URI(url).filename() // File name with file extension
   return file.substring(0, file.lastIndexOf('.')) // Remove the extension
}

Here's a snippet with test cases to play around with. All cases pass except drive paths.

test('Dots in file name without URL', 'dotted.file.name.png', 'dotted.file.name')
test('Dots in file name with URL', 'http://example.com/file.name.txt', 'file.name')
test('Lengthy URL with parameters', '/my/folder/filename.html#dssddsdsd?toto=33&dududu=podpodpo', 'filename')
test('URL with hash', '/my/folder/filename.html#dssddsdsd', 'filename')
test('URL with query strings', '/my/folder/filename.html?toto=33&dududu=podpodp', 'filename')
test('Hash after query string', 'http://www.myblog.com/filename.php?year=2019#06', 'filename')
 test('Query parameter with file path character', 'http://www.example.com/filename.zip?passkey=1/2', 'filename')
test('Query parameter with file path character and hash', 'http://www.example.com/filename.html?lang=en&user=Aan9u/o8ai#top', 'filename')
test('Asian characters', 'http://example.com/文件名.html', '文件名')
test('URL without file name', 'http://www.example.com', '')
test('Null', null, '')
test('Undefined', undefined, '')
test('Empty string', '', '')
test('Drive path name', 'C:/fakepath/filename.csv', 'filename')

function fileName(url) {
   if (url === null || typeof url === 'undefined')
      return ''
   let file = new URI(url).filename() // File name with file extension
   return file.substring(0, file.lastIndexOf('.')) // Remove the extension
}

function test(description, input, expected) {
   let result = fileName(input)
   let pass = 'FAIL'
   if (result === expected)
      pass = 'PASS'
   console.log(pass + ': ' + description + ': ' + input)
   console.log('  =>  "' + fileName(input) + '"')
}
<script src="https://cdn.jsdelivr.net/gh/medialize/[email protected]/src/URI.js"></script>

Results

PASS: Dots in file name without URL: dotted.file.name.png
  =>  "dotted.file.name"
PASS: Dots in file name with URL: http://example.com/file.name.txt
  =>  "file.name"
PASS: Lengthy URL with parameters: /my/folder/filename.html#dssddsdsd?toto=33&dududu=podpodpo
  =>  "filename"
PASS: URL with hash: /my/folder/filename.html#dssddsdsd
  =>  "filename"
PASS: URL with query strings: /my/folder/filename.html?toto=33&dududu=podpodp
  =>  "filename"
PASS: Hash after query string: http://www.myblog.com/filename.php?year=2019#06
  =>  "filename"
PASS: Query parameter with file path character: http://www.example.com/filename.zip?passkey=1/2
  =>  "filename"
PASS: Query parameter with file path character and hash: http://www.example.com/filename.html?lang=en&user=Aan9u/o8ai#top
  =>  "filename"
PASS: Asian characters: http://example.com/文件名.html
  =>  "文件名"
PASS: URL without file name: http://www.example.com
  =>  ""
PASS: Null: null
  =>  ""
PASS: Undefined: undefined
  =>  ""
PASS: Empty string: 
  =>  ""
FAIL: Drive path name: C:/fakepath/filename.csv
  =>  ""

This solution is for you if you're too lazy to write custom code and don't mind using a library to do work for you. It isn't for you if you want to code golf the solution.

A URL or a web address, often has a file name, with few parameters occasionally. Sometimes, we might need to know only the file name in the URL. There's a simple technique to extract the file name from a url in JavaScript.

How to replace a String with another String in the URL Bar using JavaScript or jQuery

We want the file name from the url. But, first we need a url. You can use window.location.href to get the url of the current page or you can simply use the complete web address.

<script>
    let url = window.location.href;
    alert (url);
</script>

Try it

The alert will show the complete url (the web address), which will have the file name and few parameter etc. To get only the file name, I'll use the split() and pop() functions.

<script>
    let url = window.location.href;
    let filename = url.split('/').pop();
    alert (filename);
</script>

Try it

The split() function creates an array of string, after removing all the forward slash (/) from the url string. The pop() function will return the last element, which is file name, from the array. And that's what we want.

How to check if the URL bar contains a Specified String in JavaScript and jQuery

Things get a little tricky, when the url has parameters (also called query strings or variables) and other information. A url with query string may look like this.

https://www.encodedna.com/javascript/practice-ground/default.htm?pg= accordion_menu_using_jquery_css

The above (second) example will not be able to return the file name in this case. Because the split() in the second example, removes the forward slashes only. The query string now have a question mark (?). We need to get rid of this too. Here's how we can do this.

<script>
    let url = window.location.href;
    let filename = url.split('/').pop().split('?')[0];
    alert (filename);
</script>

Try it

Its super easy to get the FileName and File Extension from a URL in Asp.Net using C# and Vb

Now, it will split, pop and split again, to get the file name. Similarly, the url may have multiple parameters separated by &, it may # and lots of other information. In such cases, you might have to use the split() function multiple times.

<script>
    var url = window.location.href;
    var filename = url.split('/').pop().split('?')[0].split('#')[0];
    alert (filename);
</script>

How to pass multiple variables or parameters using a QueryString in Asp.Net

That's it. Thanks for reading.

← PreviousNext →

How to extract file name from url?

The filename is the last part of the URL from the last trailing slash. For example, if the URL is http://www.example.com/dir/file.html then file. html is the file name.

How to get document name in JavaScript?

check the doc name in javascript.

var path = window. location. pathname;.

var page = path. split("/"). pop();.

console. log( page );.