Reputation: 923
Can I get the current .php or .html file name by JavaScript? The script is in the external file in respect to current .php or .html, so need the name file name of this current .html of .php:
<!DOCTYPE html>
<html>
<head>
...
<script src="js/Script.js" type="text/javascript"></script>
</head>
<body>
...
</body>
</html>
I tried this but the variable value was empty, maybe because currently I use the local host. Anything that can to do which will be work on both local and remote host?
Upvotes: 1
Views: 5864
Reputation: 1
Create following function to get the current .php or .html file's name in JavaScript.
const getCurrentFile = () => {
let url = window.location.href;
let objs = url.split("/");
return (objs[objs.length-1]);
}
Here, with the help of JavaScript's split function, we splits the url with "/" and then returned the last element.
Upvotes: 0
Reputation: 46
Verify if this document can help you.
It must be something, like this:
var page = window.location.href;
Upvotes: 1
Reputation: 2213
Below is the simple code to get full URL and filename of URL:
Example1:
var url=location.href;
var urlFilename = url.substring(url.lastIndexOf('/')+1);
OUTPUT1:
url => http://localhost/demo/index.php
urlFilename => index.php
OUTPUT2:
url => http://localhost/demo/
urlFilename =>
urlFilename will be empty in case of url is rewritten to (http://localhost/demo/)
Example2: I do not know if you want to use php inside javascript, if you are desperate to get the filename this is one way to do it.
var filename = '<?= __FILE__?>';alert(filename);
//output: ex: /opt/lampp/htdocs/demo/index.php
var url2 = filename.substr(filename.lastIndexOf('/')+1);
//output: ex: index.php
Upvotes: 3