Saturday, February 19, 2011

Does JavaScript support verbatim strings?

In C# you can use verbatim strings like this:

@"\\server\share\file.txt"

Is there something similar in JavaScript?

From stackoverflow
  • No, there isn't support for that in JavaScript. And that workaround seems very problematic as you now lose the ability to have forward slashes.

    I've run into this issue myself when I needed to build an alert message or something from an ASP.NET back end, and stick it in a JavaScript alert on the front end. The issue was that developers could enter anything in the Page.Alert() method.

    What I did to solve this was as follows:

    public void Alert(string message)
    {
        message = message.Replace("\\", "\\\\")
            .Replace("\r\n", "\n")
            .Replace("\n", "\\n")
            .Replace("\t", "\\t")
            .Replace("\"", "\\\"");
    
        // and now register my JavaScript with this safe string.
    }
    
    PhiLho : It was only an example, well suited to the given question (Windows path). You can replace / by any character.
  • I'll re-iterate what's been said before - verbatim strings aren't possible in javascript. It's actually easy to escape valid escape characters like \n \\ \t etc but the problem comes from escaping non-valid characters due to the way they are handled in the different functions they become incompatible. For example

    "\a".replace("\a","\\a")     // WORKS \a
    "aa\a".replace("\a", "\\a")  // FAILS \aaa
    

    Also if you look at an array of illegal special characters eg ["\a"] the character will jsut look like an a. This makes doing what you want essentially impossible.

    Hope that at least clears it up for you.

  • Big kludge of a workaround...

    <html>
    <head>
    <script>
    function foo() {
        var string = document.getElementById('foo').innerHTML;
        alert(string);
    }
    window.onload=foo;
    </script>
    <style>
    #foo{
      display: none;
    }
    </style>
    </head>
    <body>
    Calling foo on page load.
    <div id="foo">\\server\path\to\file.txt</div>
    </body>
    </html>
    

0 comments:

Post a Comment