16

I'm trying to extract the current file name in Javascript without any parameters.

$(location).attr('href').match(/([a-zA-Z\-\_0-9]+\.\w+)$/);
var current_path = RegExp.$1;
if ((current_path == 'index.html') || ...) {
  // something here
}

But it doesn't work at all when you access like http://example.com/index.html?lang=ja. Sure before the file name will be changed at random.

Any idea?

Henrik Erlandsson
  • 3,797
  • 5
  • 43
  • 63
Kei Izumi
  • 167
  • 1
  • 1
  • 6
  • 1
    Wow, you need to learn some javascript. `$(location).attr('href')` === `location.href` javascript is a precursor to jQuery, not the other way around – qwertymk Jul 01 '11 at 04:19
  • I answered a similar question here http://stackoverflow.com/questions/511761 – Nadir Jan 06 '15 at 14:15
  • @Kei: I edited the title to reflect that you are asking about the current path only. I hope that's OK. – Henrik Erlandsson Nov 28 '17 at 14:00

7 Answers7

52

If you're looking for the last item in the path, try this:

var current_path = window.location.pathname.split('/').pop();

This:

window.location.pathname

will give you something like:

"/questions/6543242/how-to-extract-the-filename-of-url-in-javascript"

Then the .split() will split the string into an Array, and .pop() will give you the last item in the Array.

user113716
  • 318,772
  • 63
  • 451
  • 440
  • @npe you are wrong. `location.pathname` does not return query/hash params. Ex. `http://somehost:8080/web/path/to/yourfile.txt?something=1222&another=more#andAHash` is your `location.href` then `location.pathname` returns `'/web/path/to/yourfile.txt'` – nf071590 Oct 05 '15 at 17:15
  • Note that this answer solves the asker's niche case, but doesn't support all valid URLs. – Henrik Erlandsson Nov 28 '17 at 13:57
  • I like that you didn't directly answer the OP's question. The answer is good and probably more likely to stick if you need to engage your brain rather than copy and paste like most cases. +1 – JDandChips Jan 20 '18 at 12:00
14
function filename(path){
    path = path.substring(path.lastIndexOf("/")+ 1);
    return (path.match(/[^.]+(\.[^?#]+)?/) || [])[0];
}

console.log(filename('http://example.com/index.html?lang=ja'));

// returned value: 'index.html'
kennebec
  • 102,654
  • 32
  • 106
  • 127
10

The filename of a URL is everything following the last "/" up to one of the following: 1.) a "?" (beginning of URL query), or 2.) a "#" (beginning of URL fragment), or 3.) the end of the string (if there is no query or fragment).

This tested regex does the trick:

.match(/[^\/?#]+(?=$|[?#])/);

ridgerunner
  • 33,777
  • 5
  • 57
  • 69
1

There is a URL.js library that makes it very easy to work with URLs. I recommend it!

Example

var uri = new URI('http://example.org/foo/hello.html?foo=bar');
uri.filename(); // => 'hello.html'
nekman
  • 1,919
  • 2
  • 15
  • 26
0

You can do something more simple:

var url = "http://google.com/img.png?arg=value#div5"
var filename = url.split('/').pop().split('#')[0].split('?')[0];

Result:

filename => "img.png"
Nourdine Alouane
  • 804
  • 12
  • 22
0

your regex isn't correct. Instead try to be more specific:

.match(/([a-zA-Z\-\_0-9]+\.[a-zA-Z]{2,4})[\?\$]/);

says:

find any number of alphanumeric or hypens[a-zA-Z\-\_0-9]+ before a fullstop that has between 2 and 4 alphabetic characters [a-zA-Z]{2,4} that combefore either the end (\$) or a question mark (\?)

tested on:

("http://www.example.com/index.html?lang=ja").match(/([a-zA-Z\-\_0-9]+\.[a-zA-Z]{2,4})[\?\$]/);
var current_path = RegExp.$1;
alert(current_path);
James Khoury
  • 21,330
  • 4
  • 34
  • 65
0

try this:

window.location.pathname.substring(1)
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164