2

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

2 Answers 2

9
var loc = window.location.href;
var output  = loc.split('/').pop().split('.').shift()
2

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.

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.