user815460
user815460

Reputation: 1143

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!!

Upvotes: 4

Views: 2313

Answers (6)

user985399
user985399

Reputation:

I recommend to also remove 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 '?' until the end $ by empty string

Upvotes: 0

James Hill
James Hill

Reputation: 61793

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

Upvotes: 3

Slavo
Slavo

Reputation: 15463

There is a jQuery plugin that makes it easy to parse URLs and provide access to their different parts. One of the things it does is return the filename. Here's the plugin on GitHub:

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

I would recommend using that and avoid reinventing the wheel. Regular expressions is an area of programming where this is particularly applicable.

Upvotes: 0

Lachezar
Lachezar

Reputation: 6703

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

Upvotes: 1

Khodor
Khodor

Reputation: 1006

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

alert(fn.pop());

Upvotes: 0

Tetaxa
Tetaxa

Reputation: 4393

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

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

Upvotes: 4

Related Questions