Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the filename of the URL of the current document path in JavaScript?

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?

like image 302
Kei Izumi Avatar asked Jul 01 '11 03:07

Kei Izumi


3 Answers

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.

like image 108
user113716 Avatar answered Oct 12 '22 22:10

user113716


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'
like image 39
kennebec Avatar answered Oct 12 '22 23:10

kennebec


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

like image 42
ridgerunner Avatar answered Oct 12 '22 22:10

ridgerunner