0

I want to be able to insert the name of a file in running text in an HTML file, using a function For example, in the file "example1.html", the text would read "This file is called example1", and in "example2.html", it would read "This file is called example2". Both files would have the exact same code.

From here, I got this code which gets the name of an HTML file:

<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>

How can I make this into a function that I can use anywhere throughout any html file and how would I use it (excuse my almost non-existant knowledge in this language)? I want the function to be on script.js, not on each html file.

Hasan
  • 11
  • 3

1 Answers1

0

You can only introduce JS scripts into a page by using the <script> tag or by importing a script from a URL. You might try moving all of your code inside the script tag in your example into a separate .js file, and then <script src='http://yoururl.com/script.js'/>

David Min
  • 1,246
  • 8
  • 27