Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
106
rated 0 times [  108] [ 2]  / answers: 1 / hits: 37623  / 13 Years ago, fri, july 1, 2011, 12:00:00

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?


More From » jquery

 Answers
97

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.


[#91410] Wednesday, June 29, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
isaacvalentinn

Total Points: 325
Total Questions: 120
Total Answers: 131

Location: North Korea
Member since Tue, Jun 16, 2020
4 Years ago
isaacvalentinn questions
Mon, Jan 18, 21, 00:00, 3 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
Wed, Sep 23, 20, 00:00, 4 Years ago
;