Defining a long string using javascript

I have a simple problem that I just cannot understand. In the code below, I get an error (test_str is not defined) because the line defining "var str =" propagates over two lines. After the word "fox" there is CR LF, and I think my javascript engine in my browser thinks I want a new expression. Now, of course, in this example, I can just get rid of the carriage return and put it all on one line to fix this. But my real intention is to have a much longer line in some kind of production code that I really don't want to associate with deleting all these CR LFs.

<html> <head> <script> function test_str() { str = " The quick brown fox jumped over the log."; alert(str); } </script> </head> <body> <a href='javascript:void(0);' onclick='test_str();'>Test String</a> </body> </html> 
+6
source share
7 answers

Just put a \ at the end of each line, even on the line

 str = " The quick brown \ // <--- fox jumped over the log."; 
+4
source

The simplest is to add \ at the end of the line:

 function test_str() { str = " The quick brown \ fox jumped over the log."; alert(str); } 

JsFiddle example

+2
source

Try the following:

 str = " the quick brown fox\r\n" + "fox jumped over the lazy dog"; 
+1
source

Use \r\n in your line to represent CR LF:

 str = "The quick brown\r\nfox jumped over the log."; 
0
source

String literals cannot span multiple lines in JavaScript. You need to either explicitly continue each line with the following:

 var foo = "The quick brown fox\ jumped over the lazy\ dog"; 

Or combine string literals:

 var foo = "The quick brown fox " + "jumped over the lazy " + "dog"; 

I personally prefer the latter, as you will be able to backtrack it more intelligently, without paying attention to the spaces inside the line, since

 var foo = "asdf \ bar"; 

will result in a line like "asdf bar ;.

0
source

Try to slip away from the newline literal,

 str = " The quick brown \ fox jumped over the log."; 
0
source

Another way to define multi-line strings is to use an array and concatenate them. This makes it easy to define a new line character ( \n\r ) for each line, assuming you store lines by Array index ( "" without separating characters between lines). For example, the following line will be created below:

Fast brown
the fox jumped over the log.

 str = [" The quick brown ", "fox jumped over the log."].join("\n\r");//each line should be a new line 
0
source

All Articles