1

Good Morning,

I'm using a function I got from another post here:

How to get the file name from a full path using JavaScript?

To return the current filename of a webpage

var url=window.location.pathname;
var filename = url.replace(/^.*[\\\/]/, '');
alert(filename);

and I was curious as to whether it is possible to strip the .html from the end while still using this syntax.

Community
  • 1
  • 1
Deprecated
  • 163
  • 1
  • 3
  • 14

3 Answers3

2

Either specify the extensions you want to manage, to be more restrictive, using:

.replace(/^.*[\/](.*)[.](html|jsp|php)/, '$1');

Either be more generic, using:

.replace(/^.*[\/](.*)[.][a-zA-Z0-9]{2,5}/, '$1');

The second one will allow extensions from 2 chars (e.g. .do) to 5 chars (e.g. .xhtml), which could also contain numbers (e.g. .php3).

sp00m
  • 47,968
  • 31
  • 142
  • 252
  • @user1821973 I'm not sure this regex is the cause of the IE8 issue you're meeting: it must come from somewhere else in your script. But whatever, I'm glad I could help `;)` – sp00m Dec 19 '12 at 16:19
  • It is possible, sorry I jumped straight to that conclusion, here let me edit: *The regex probably works in IE8 because IE8 does support regex; however, something unforseen in my script is preventing this statement from working. – Deprecated Dec 19 '12 at 16:28
2

I think the easiest way will be

var filename = url.replace(/^.*[\\\/]/, '').replace(".html", "");
user160820
  • 14,866
  • 22
  • 67
  • 94
  • This is the most broswer comprehensive answer of all the answers, so it is the one I'm accepting; however all of the answers are great! – Deprecated Dec 19 '12 at 16:15
1

You can use a capture clause in replace:

var url=window.location.pathname;
alert(url)
var filename = url.replace(/^.*[\\\/](.*).html$/, '$1');
alert(filename);
Amir T
  • 2,708
  • 18
  • 21