Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Regex in Javascript to get the filename in a URL

I'm using JavaScript to try and get the filename 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 (e.g., without having to use fn[fn.length-1]

Thanks!!

like image 706
user815460 Avatar asked Feb 22 '23 12:02

user815460


2 Answers

Add a $ at the end so you only get the last part:

window.location.href.match(/[^/]+$/g);
like image 91
Tetaxa Avatar answered Mar 07 '23 17:03

Tetaxa


Personally, I try to use simple string manipulation for easy tasks like this. It 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

Not that it matters for something so trivial, but this method is also more performant than RegEx: http://jsperf.com/get-file-name

like image 27
James Hill Avatar answered Mar 07 '23 17:03

James Hill