When talking about path-related issues, everyone will think about window.location. It is true that this object provides a lot of path information, and the commonly used ones include:
1.location.href: The full URL of the current page
2.location.pathname: the path name in the current URL
3.location.hash: anchor point in the current URL
4.location.search: query parameters in the current URL
However, location does not have a property that directly obtains the absolute path to the current directory (excluding the file name). Through Google, I found some wrong methods, such as separating the URL into an array through "/", removing the last item of the array and then concatenating it into a string. But if the file name is not specified in the URL, the result is a big mistake.
According to previous coding experience, the href attribute of the a element always returns an absolute path, which means it has the ability to convert the relative path into an absolute path. I tried it with the following code and it turned out to be:
The code copy is as follows:
var a = document.createElement('a');
a.href = './';
alert(a.href);
a = null;
Unfortunately, this method does not work under old IE 6/7, and when alert(a.href) is executed, the pop-up is still "./". Later, I found that someone raised this problem on Stackoverflow, and the solution is also very simple. Just inject a through innerHTML:
The code copy is as follows:
var div = document.createElement('div');
div.innerHTML = '<a href="./"></a>";
alert(div.firstChild.href);
div = null;
Someone may ask: Why not use regular expressions? My answer is: considering whether there is a file name, an anchor point, and a query parameter, this regular expression may be quite complicated.