简体   繁体   中英

Why use forward slash '/' instead of backward slash '\' in relative paths in JavaScript?

In the little JavaScript I wrote, the 'src' attribute of 'img' element accepted and displayed the image only if I changed '\\' to '/' in the relative path of the image.

Why is it so?

<html>
  <body>

   <img id="image" src="F:\wallpapers\other\black-and-white-lion-chess-hd-531078.jpg">
   //why did '\' work here?

   <script>

    document.getElementById("image").src="F:/wallpapers/other/clouds_nature_skyscapes.jpg";
    //why didn't '\' work here? Why did I have to use '/' ?
  </script>

  </body>
</html>

A single \\ character in a Javascript string is used to "escape" the next character, eg \\n is used for the newline character. See this

In your example, if you want to use windows path names, use \\\\ as path separator, like so: F:\\\\wallpapers\\\\other\\\\clouds_nature_skyscapes.jpg

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM