Reputation: 2588
I am hoping to find only the filename within the current page URL.
So if the URL is
www.ex.com/des/filename.php
or
www.ex.com/des/filename.php#9
I need to get only
filename
I tried this, but it doesn't work.
var loc = window.location;
var fileNameIndex = loc.lastIndexOf("/") + 1;
var output = loc.substr(0, loc.lastIndexOf('.')) || loc;
Thanks
Upvotes: 2
Views: 5589
Reputation: 1844
var loc = window.location.href;
var output = loc.split('/').pop().split('.').shift()
Upvotes: 9
Reputation: 1120
This works for me:
var loc = window.location.href
var fileNameIndex = loc.lastIndexOf("/") + 1;
var dotIndex = loc.lastIndexOf('.');
var output = loc.substr(fileNameIndex, dotIndex < fileNameIndex ? loc.length : dotIndex);
For an explanation of the code: What it does is, it takes the text between the last "/" and the last ".", provided the "." occurs after the "/", otherwise it just takes everything from the last "/" to the end of the string.
Upvotes: 2