我有一个模板html文件,有几个人使用。他们制作副本然后重新编辑它。我试图在模板文件中放入一些内联js,以便title标签的innerHTML自动填充文件名。这就是我所拥有的。效果很好。唯一的问题是我不想包含文件扩展名。没有多行代码的任何简单方法来摆脱文件扩展名?
<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>
这解决了我的问题。只是想知道是否有更简单的方法来做到这一点:
<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>