用JavaScript定义一个长字符串

9

我有一个简单的问题,但是我就是无法解决。在下面的代码中,我会遇到一个错误(test_str没有被定义),因为“var str=”这一行代码被分成了两行。在单词“fox”后面有一个回车换行符,我猜我的浏览器中的JavaScript引擎认为我想在那里创建一个新语句。现在当然,在这个例子中,我可以简单地删除回车换行符并将其全部放在一行上以进行修复。但是我的真实意图是针对一些生产代码中更长的字符串,我真的不想删除所有这些回车换行符。

<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
在JavaScript中创建多行字符串:https://dev59.com/c3RA5IYBdhLWcg3w2xsI - KayakDave
7个回答

4
只需在字符串中每行末尾添加\即可。
str = "  The quick brown \  // <---
fox jumped over the log.";

2
最简单的方法是在每行末尾添加\
function test_str() {
  str = "  The quick brown \
  fox jumped over the log.";
  alert(str);
}

jsFiddle示例


1
使用\r\n在字符串中表示回车换行:
str = "The quick brown\r\nfox jumped over the log.";

1

试试这个:

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

0

JavaScript中的字符串文字不能跨越多行。您需要将每一行明确地延续到下一行:

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

或者将字符串字面值连接起来:

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

个人而言,我更喜欢后者,因为您可以更合理地缩进它,而不需要太关注字符串内的空格,因为

var foo = "asdf \
           bar";

会产生一个类似于 "asdf           bar" 的字符串。


0

尝试转义换行符字面值,

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

0
定义多行字符串的另一种方法是使用数组并将它们连接起来。这样就可以很容易地为每一行定义一个新的行字符(\n\r),假设您按数组索引存储行(""表示行间没有分隔符)。例如,下面的代码将创建以下字符串:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接