简体   繁体   中英

What is the javascript antislash and how does it work with multi-line strings?

I was looking for a way to do multi-line strings in javascript. And I used came across this bit of code:

var str = <><![CDATA[
This string spans multiple lines
Doesn't need quoting of single quotes
And the same goes for "double quotes".
Because of the CDATA, I can also include some <b>html</b>
Which can make use of <attributes with="double quotes"/> but at the same
time, I can make use of the > and < signs without worrying about
xml validity.
]]></>;

When using this piece of code in Visual Studio 2012, I get error lines. Also, I've never used CDATA in Javascript or HTML, so I'm not sure how this is supposed to work.

So, 1, can this code (with some tweaking) work? 2, what is the antislash?

Source 1

Source 2

That code you posted is not valid Javascript. If your script is embedded within an X[HT]ML document, the CDATA trick may work, but I suspect it still wouldn't, because it would be translated to literal newlines before the Javascript interpreter saw it. In any case, a string literal containing unescaped newlines is a syntax error.

If by "antislash" you mean the \\ character (normally called "backslash"), it can be used (at least in interpreters conforming to the 4th or later edition of the ECMAScript specification ) to continue a literal string onto the next line. But when you do so, you are not really creating a "multiline string", because both the backslash and the newline are omitted from the string result.

var s = "abc \
         123"
console.log(s)  //= abc 123

(I indented for clarity above, but if you do that, the result is implementation-dependent - some JS interpreters squash the extra whitespace after the LineContinuation, while others do not.)

The usual solution in Javascript is to use explicit newlines and concatenation:

var z = "abc\n" +
        "123"
console.log(z)   //=  abc
                 //   123

Or perhaps something like this (is this what you meant, @torazaburo?):

[
    "abc",
    "123",
    "third line",
    "another line"
].join("\n")

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