简体   繁体   中英

Escape Javascript String in Double Quotes

Well i have a long string in double quotes

var Variable = "Really Long ...... String"

I would want to do this

var Variable = "Really
                Long
                ...... 
                String"

Currently I do this

var Variable = "Really\n\
                Long\n\
                ......\n\
                String"

It works correctly across all browsers. But is it the correct way to do it?

I think using the plus sign might be more effective.

var Variable = "Really " +
                "Long " +
                "...... " +
                "String";

In your example above, how do you know how many spaces are before the word "Long", for example? I would not count on that being consistant across browsers.

My understanding is that using the plus sign to concatentate strings is just as efficient...javascript parsers are smart enough to handle that the same way as your example.

I'd recommend just joining it.

var str = [
   'This is a very long piece ',
   'of string that I\'m going to join together ',
   'right about now.'
].join('')

You can use an array and join the values. But I am not sure about performance. If you use string concatenation, it can (and most likely will) be optimized by the engine (meaning it generates one string on parsing the code), but whether engines are so smart to discover a simple join with an array.... I don't think so.

var Variable = ["Really ",
                "Long ",
                "...... ",
                "String"].join('');

JavaScript does not support "here documents" as PHP does, so you can't do much better. You will end up with many spaces at the beginning of lines though (if you indent the code the way you present it here). To avoid that, use string concatenation:

var Variable = "Really\n" +
"Long\n" +
"String";

Or array joining (as suggested by meder):

var Variable = [
    "Really",
    "Long",
    "String"
].join('\n');

The LineContinuation is a new feature in ECMA-262 5th edition (§7.8.4). If you absolutely must comply to ECMAScript 3, avoid it and use + or .join('') or whatever. But as you've mentioned, this particular feature is supported among major browsers (even IE 6) [1] , I see no strong reason to avoid this other than having a coding convention.

(Ref: [1] http://shwup.blogspot.com/2009/05/line-continuation-in-javascript.html )

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