我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?

text = <<"HERE"
This
Is
A
Multiline
String
HERE

当前回答

至少在源代码方面,这是一种相当经济的方法:

function s() {
    var args = [],index;
    for (index = 0; index< arguments.length; index++) {
        args.push (arguments [index]);
    }
    return args.join ("\n");
}
console.log (s (
    "This is the first line",
    "and this is the second",
    "finally a third"
));

function s() {return arguments.join ("\n")} 

如果“arguments”属性是一个正确的数组,当然会更好。

第二个版本可能使用“”来进行连接,当您想要控制非常长的字符串中的换行符时。

其他回答

我通过输出一个div,使其隐藏,并在需要时通过jQuery调用div id来解决这个问题。

e.g.

<div id="UniqueID" style="display:none;">
     Strings
     On
     Multiple
     Lines
     Here
</div>

然后,当我需要获取字符串时,我只需使用以下jQuery:

$('#UniqueID').html();

它会在多行上返回我的文本。如果我打电话

alert($('#UniqueID').html());

我得到:

我找到了一个更优雅的解决方案,可能有点与主题无关,因为它使用了PHP,但我相信它对你的一些人来说会很有用和可爱。。。

这个javascript代码应该留在脚本标记中

var html=<?php echo json_encode("

        <div class=container>
            <div class=area1>
                xxx
            </div>
            <div class=area2>
                ".$someVar."
            </div>
        </div>

"); ?>

在输出html中,您将看到类似

var html="\r\n\r\n\t\t\t<div class=container>\r\n\t\t\t\t<div class=area1>\r\n\t\t\t\t\txxx\r\n\t\t\t\t<\/div>\r\n\t\t\t\t<div class=area2>\r\n\t\t\t\t\t44\r\n\t\t\t\t<\/div>\r\n\t\t\t<\/div>\r\n\r\n\t\t";  

 


瞧!,它为您的文件提供了代码可读性。

pD:此示例使用json_encode()PHP函数,但当然也有ASP、Ruby和JSP语言的等效函数。

pD:然而,这个解决方案也有他的局限性,其中之一就是不能在封装的代码中使用javascript变量。

这适用于IE、Safari、Chrome和Firefox:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<div class="crazy_idea" thorn_in_my_side='<table  border="0">
                        <tr>
                            <td ><span class="mlayouttablecellsdynamic">PACKAGE price $65.00</span></td>
                        </tr>
                    </table>'></div>
<script type="text/javascript">
    alert($(".crazy_idea").attr("thorn_in_my_side"));
</script>

规则是:当在字符串中时,在需要换行的地方使用;您不必在JavaScript之前或之后放置空格,JavaScript的解释器足够聪明,可以知道不可打印字符表示的长度。

我认为这个解决方法应该适用于IE、Chrome、Firefox、Safari和Opera-

使用jQuery:

<xmp id="unique_id" style="display:none;">
  Some plain text
  Both type of quotes :  " ' " And  ' " '
  JS Code : alert("Hello World");
  HTML Code : <div class="some_class"></div>
</xmp>
<script>
   alert($('#unique_id').html());
</script>

使用纯Javascript:

<xmp id="unique_id" style="display:none;">
  Some plain text
  Both type of quotes :  " ' " And  ' " '
  JS Code : alert("Hello World");
  HTML Code : <div class="some_class"></div>
</xmp>
<script>
   alert(document.getElementById('unique_id').innerHTML);
</script>

干杯