The absolute path method used in JavaScript to get the current directory using the A tag

Source: Internet
Author: User
Tags regular expression

This article mainly introduces the JavaScript uses a tag to obtain the current directory absolute path method, this article explains the method to be quite special, needs the friend to be possible to refer to under

When it comes to path-related issues, everyone will go to the window.location and think that this object provides quite a lot of path information, which is commonly used to include:

1.location.href: Full URL of the current page
2.location.pathname: path name in current URL
3.location.hash: Anchor points in the current URL
4.location.search: Query parameters in the current URL

However, location does not have an attribute that directly obtains the absolute path of the current directory (without the filename). Through Google I found some wrong ways, such as the URL through "/" separated by the number of groups, the last item of the array is removed and then connected to a string. However, if a filename is not specified in the URL, the result is wrong.

Based on previous coding experience, the href attribute of a element always returns an absolute path, which means it has the ability to turn a relative path into an absolute path. Try it with the following code:

The code is as follows:
var a = document.createelement (' a ');
A.href = './';
alert (A.HREF);
A = null;
Unfortunately, this method is not valid under old IE 6/7, and when executing alert (A.HREF), the pop-up is still "./". Later, I found that some people in the StackOverflow also raised the problem, and the solution is very simple, as long as a through innerHTML injection can be:
The code is as follows:
var div = document.createelement (' div ');
div.innerhtml = ' <a href= './"></a>";
alert (DIV.FIRSTCHILD.HREF);
div = null;
One might ask: why not use regular expressions? My answer is: to consider whether there is a file name, there is no anchor point, there is no query parameters, this regular expression may be quite complex.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.