9

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>
1

7 Answers 7

4

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

str = "  The quick brown \  // <---
fox jumped over the log.";
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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

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

Comments

1

Try this:

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

Comments

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".

Comments

0

Try escaping the newline literal,

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.