8

I have a simple problem that I just can't seem to figure out. In the code below I get an error (test_str is not defined) because the line defining "var str=" is spread across two lines. After the word "fox" there is a CR LF and I guess my javascript engine in my browser thinks I want a new statement there. Now of course in this example I can simply get rid of the carriage return and put it all on one line to fix it. But my real intent is for a much longer string in some production code which I don't really want to mess with deleting all those CR LF's.

<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>
Thread7
  • 1,081
  • 2
  • 14
  • 28
  • 1
    creating-multiline-strings-in-javascript: http://stackoverflow.com/questions/805107/creating-multiline-strings-in-javascript – KayakDave Dec 30 '13 at 18:17

7 Answers7

4

Just put a \ at the end of each line still in the string

str = "  The quick brown \  // <---
fox jumped over the log.";
Deryck
  • 7,608
  • 2
  • 24
  • 43
2

Easiest thing to do is to add a \ at the end of the lines:

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

jsFiddle example

j08691
  • 204,283
  • 31
  • 260
  • 272
1

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

str = "The quick brown\r\nfox jumped over the log.";
Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
1

Try this:

str = " the quick brown fox\r\n" + 
  "fox jumped over the lazy dog";
snowdude
  • 3,854
  • 1
  • 18
  • 27
0

String literals can't span multiple lines in JavaScript. You'll need to either explicitly continue each line onto the next:

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

Or concatenate string literals:

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

I personally prefer the latter, as you'll be able to indent it more reasonably without as much regard to whitespace within the string, since

var foo = "asdf \
           bar";

would result in a string like "asdf           bar".

Chris W.
  • 927
  • 8
  • 16
0

Try escaping the newline literal,

str = "  The quick brown \
      fox jumped over the log.";
addy2601
  • 387
  • 2
  • 12
0

Another way to define multi line strings is to use an Array and join them. This allows you to easily define a new line character (\n\r) for each line assuming you store lines by Array index ("" for no character seperation between lines). For instance below will create the following string:

The quick brown
fox jumped over the log.

str = ["  The quick brown ",
  "fox jumped over the log."].join("\n\r");//each line should be a new line
megawac
  • 10,953
  • 5
  • 40
  • 61