Use the label in javascript to obtain the absolute path of the current directory

Source: Internet
Author: User

1. location. href: complete url of the current page
2. location. pathname: The path name in the current url
3. location. hash: the anchor in the current url
4. location. search: query parameters in the current url

However, location does not have an attribute to directly obtain the absolute path of the current directory (excluding the file name. I found some incorrect methods through google. For example, the url is separated into an array by "/", and the last entry of the array is removed and then connected to a string. However, if the file name is not specified in the url, the result is very wrong.
Based on past coding experience, the href attribute of element a always returns an absolute path, that is, it has the ability to convert the relative path to an absolute path. I tried the following code and it turned out to be:

Vara = document. createelement ('A ');
A. href = './';
Alert (a. href );
A = null;

Unfortunately, this method is invalid in the old ie 6/7. When you execute alert (a. href), the pop-up is still "./". Later, I found someone raised this issue in stackoverflow, and the solution is very simple. Just inject a through innerhtml:
The code is as follows:

Vardiv = document. createelement ('div ');
Div. innerhtml = '<ahref =./> </a>;
Alert (div. firstchild. href );
Div = null;

Some may ask: why not use a regular expression? My answer is: this regular expression may be quite complicated to consider whether there is a file name, an anchor, or a query parameter.

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.