0

I have a template html file that several people use. They make a copy and then they retitle it. I am trying to put some inline js inside the template file so that the innerHTML of the title tag is automatically filled with the name of the file. This is what I have. Works great. The only problem is I don't want the file extension included. Any simple way to get rid of the file extension without multiple lines of code?

<title id="title">This is replaced by the name of the file</title>
<script type="text/javascript">
    var url = window.location.pathname;
    document.getElementById("title").innerHTML = url.substring(url.lastIndexOf('/')+1);
</script>

This solved my question. Just wondering if there was a simpler way to do this:

<title id="title">This is replaced by the filename</title>
<script type="text/javascript">
    var url = window.location.pathname; // gets the pathname of the file
    var str = url.substring(url.lastIndexOf('/')+1); // removes everything before the filename
    str = str.substring(0, str.length - 5); // removes the extension
    var filename = str.replace(/%20/g, " "); // if the filename has multiple words separated by spaces, browsers do not like that and replace each space with a %20. This replace %20 with a space.
    document.getElementById("title").innerHTML = filename;
</script>
A.C.
  • 15
  • 1
  • 5
  • url.substring(0, input.lastIndexOf('.')) || url; – Poldo Jul 13 '17 at 01:36
  • Doesn't work for me Paul. I replaced my url.substring(url.lastIndexOf('/')+1); with your code. – A.C. Jul 13 '17 at 01:44
  • no that didn't work either. Thanks for the help though. I did find a solution, but still wondering if there is a simpler way. See edited question. – A.C. Jul 13 '17 at 01:57
  • try to use url.lenght url = url.substring(url.lastIndexOf("/") + 1, url.length); – Poldo Jul 13 '17 at 02:01

0 Answers0