How to find the filename without the extension thr

2019-02-15 17:32发布

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

标签: filenames
2条回答
你好瞎i
2楼-- · 2019-02-15 17:54
var loc = window.location.href;
var output  = loc.split('/').pop().split('.').shift()
查看更多
贪生不怕死
3楼-- · 2019-02-15 18:01

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.

查看更多
登录 后发表回答