Does javascript have literal strings?

后端 未结 6 1929
醉酒成梦
醉酒成梦 2020-12-05 12:48

In c# and ruby and many other languages you can denote a string as to not need escaping.
in c# its like this



        
相关标签:
6条回答
  • 2020-12-05 13:04

    Short answer: No

    Long answer: Noooooooooooooooooooooooooo

    0 讨论(0)
  • 2020-12-05 13:08

    I don't know what you're getting at, but one way to get around the problem of escaping (etc) is use a trick that John Resig seems to like a lot. You include <script> blocks in a page, but give them a "type" like "text/plain" to make sure that the browser doesn't hand them over to Javascript. Then use the text of the script block for whatever you like.

    <script id='a_string' type='text/plain'>
      Here is some stuff.
      There might be some \escape sequences in it.
    </script>
    

    Then you can grab that with $('#a_string').text() (or with getElementById if you're not using jQuery or something like that).

    edit: Here's John Resig's explanation about why dropping stuff into script blocks like that is a good idea:

    Quick tip: Embedding scripts in your page that have a unknown content-type (such is the case here - the browser doesn't know how to execute a text/html script) are simply ignored by the browser - and by search engines and screenreaders. It's a perfect cloaking device for sneaking templates into your page. I like to use this technique for quick-and-dirty cases where I just need a little template or two on the page and want something light and fast.

    Taken from this page: http://ejohn.org/blog/javascript-micro-templating/

    0 讨论(0)
  • 2020-12-05 13:08

    Literal strings are available through the use of ES6 language features. Node v4.x now supports these and around 90% of the other ES6 additions as well.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings

    In JS string literals are known as Template Strings. And the syntax is pretty straight forward.

    0 讨论(0)
  • 2020-12-05 13:19

    Just escape the escapes

    var myCrazyString = "\\yes\\we\\have\\no\\bananas"
    
    0 讨论(0)
  • 2020-12-05 13:22

    I know it is six years late now, but I've got one solution to this ;)

    function literalString(regex) {
        return ('' + regex).slice(1, -1);
    };
    
    O.innerHTML = literalString(/\whatever\this\is/);
    <pre id=O>

    You basically convert a regex to string and removes the first and last characters.

    0 讨论(0)
  • 2020-12-05 13:29

    This will work as long as you don't throw a \x into the string!

    var str = String.raw`\whatever\this\is`;
    
    console.log(str);

    0 讨论(0)
提交回复
热议问题