Use Regex in Javascript to get file name in url

I use JavaScript to try to get the file name from the URL.

I can get it using this:

var fn=window.location.href.match(/([^/])+/g); alert(fn[fn.length-1]); // get the last element of the array 

but is there an easier way to get it (for example, without using fn [fn.length-1]

Thanks!!

+4
source share
6 answers

Add $ to the end so that you get only the last part:

 window.location.href.match(/[^/]+$/g); 
+3
source

Personally, I try to use simple string manipulation for such simple tasks. This makes for more readable code (for a person not very familiar with RegEx).

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

Or simply:

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

Additional Information

It doesn't matter if it is so trivial, but this method is also more efficient than RegEx: http://jsperf.com/get-file-name

+3
source

How about: window.location.href.match(/\/([^/]+)$/)[1];

+1
source

you can use .pop () to get the last element of the array;

 alert(fn.pop()); 
0
source

There is a jQuery plugin that makes it easy to parse URLs and provide access to their various parts. One of the things she does is return the file name. Here is the plugin on GitHub:

https://github.com/allmarkedup/jQuery-URL-Parser

I would recommend using this and not reinventing the wheel. Regular expressions are a programming area where this is especially applicable.

0
source

I recommend also removing any "#" or "?" string, so my answer is:

 var fn = window.location.href.split('/').pop().replace(/[\#\?].*$/,''); alert(fn); 

split('/').pop() removes the path
replace(/[\#\?].*$/,'') replace '#' or '?' to the end of $ on an empty line

0
source

Source: https://habr.com/ru/post/1379465/


All Articles