【问题标题】:Defining a long string with javascript [duplicate]用javascript定义一个长字符串[重复]
【发布时间】:2014-01-17 15:58:15
【问题描述】:

我有一个简单的问题,我似乎无法弄清楚。在下面的代码中,我收到一个错误(未定义 test_str),因为定义“var str=”的行分布在两行中。在“狐狸”这个词之后有一个 CR LF,我猜我的浏览器中的 javascript 引擎认为我想要一个新的声明。当然,在这个例子中,我可以简单地去掉回车并将其全部放在一行上来修复它。但我的真正意图是在一些生产代码中使用更长的字符串,我真的不想删除所有那些 CR LF。

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

【问题讨论】:

标签: javascript jquery


【解决方案1】:

另一种定义多行字符串的方法是使用数组并将它们连接起来。这允许您轻松地为每行定义一个新行字符 (\n\r),假设您按数组索引存储行("" 行之间没有字符分隔)。例如下面将创建以下字符串:

快速棕色
狐狸跳过了原木。

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

【讨论】:

    【解决方案2】:

    尝试转义换行文字,

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

    【讨论】:

      【解决方案3】:

      字符串文字不能跨越 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”这样的字符串。

      【讨论】:

        【解决方案4】:

        试试这个:

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

        【讨论】:

          【解决方案5】:

          最简单的做法是在行尾添加\

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

          jsFiddle example

          【讨论】:

            【解决方案6】:

            只需在字符串中的每一行末尾添加一个\

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

            【讨论】:

              【解决方案7】:

              在你的字符串中使用 \r\n 来表示 CR LF :

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

              【讨论】:

                猜你喜欢
                • 2011-03-24
                • 2015-03-26
                • 1970-01-01
                • 2023-04-01
                • 1970-01-01
                • 2020-07-11
                • 2017-11-09
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多