Path String Format for JavaScript

Path String Format for JavaScript thumbnail
By default, Javascript assumes path names conform to Web standards.

Javascript is a powerful scripting language recognized by most modern Web browsers. Designed to work with Web files and URLs, it returns path strings in a format that browsers can easily understand, instead of paths that the operating system recognizes. As a result, passing input between Javascript and computer languages not designed as an Internet standard requires some extra steps.

  1. Paths in Javascript

    • Javascript automatically knows the path -- the address -- of the file that's calling it, so you can access it whenever you want. When you access your document's path with Javascript, it will always reformat the path into a universal resource identifier, eliminating special characters and changing file separators to forward slash symbols. This path may be different from the default path format of your operating system; for instance, the Windows operating system uses backslashes to delineate file folder names.

    URLs and Paths

    • You can read the path of your document in several ways. The first uses "document.location.pathname" to return as much of the path as the script has access to -- if the script is a Web document, it will go to the part of the file system that is public to the Web. The other way employs "document.URL" or "document.location.href" to get the document's URL directly, returning either a file path, in the case of a document saved in a folder, or the Web address of the file.

    Percent Encoding

    • Some file names contain reserved characters, which have special meaning in Javascript and other Web languages. When a Javascript encounters a path including these characters or a character that's not part of the ASCII encoding, it will automatically replace them with a percent encoding -- the percent sign followed by two hexadecimal digits. For instance, if your path contains a space in it and you access it via "document.location.pathname" or a similar variable, the string the script will return will contain "%20" in place of the spaces in the path name.

    URI Encodings

    • Javascript can convert your text between Web-formatted path strings and non-formatted strings. The function "encodeURI()" converts the string you give it into a Web-formatted string, and the function "decodeURI()" performs the reverse function, changing percent encodings to their corresponding character. However, "encodeURI()" will change any backslashes to "%5C"; if you're trying to convert a Windows path string to a URI, you will have to replace the backslashes with forward slash characters before encoding.

Related Searches:

References

  • Photo Credit Ryan McVay/Photodisc/Getty Images

Comments

Related Ads

Featured