17

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?

3
  • 1
    Wow, you need to learn some javascript. $(location).attr('href') === location.href javascript is a precursor to jQuery, not the other way around Commented Jul 1, 2011 at 4:19
  • I answered a similar question here stackoverflow.com/questions/511761 Commented Jan 6, 2015 at 14:15
  • @Kei: I edited the title to reflect that you are asking about the current path only. I hope that's OK. Commented Nov 28, 2017 at 14:00

7 Answers 7

54

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@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'
Note that this answer solves the asker's niche case, but doesn't support all valid URLs.
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
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'

Comments

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(/[^\/?#]+(?=$|[?#])/);

Comments

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'

1 Comment

You are not seriously recommending a library for this are you? That's overkill.
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);

Comments

0

try this:

window.location.pathname.substring(1)

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.