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

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

当前回答

我想我发现了另一种方法,可以在没有任何侵入性语法的情况下,在每一行中内联执行。使用Javascript将函数转换为字符串并使用/**/语法创建多行注释,然后删除“function(){/*\n”和“\n*/}”。

var multiline = function(string) { return string.toString().replace(/(^[^\n]*\n)|(\n\*\/\})/g, ""); };

console.log(multiline(function() {/*
Hello world!
I'm a multiline string!

Tada!
*/}));

我能看到的唯一缺陷是语法高亮显示。

编辑:如果我再向下滚动一点,我会看到这个答案完全一样:https://stackoverflow.com/a/5571069/916553

其他回答

您可以使用+=连接字符串,似乎没有人回答,这将是可读的,也很整洁。。。像这样的东西

var hello = 'hello' +
            'world' +
            'blah';

也可以写成

var hello = 'hello';
    hello += ' world';
    hello += ' blah';

console.log(hello);

有这样一个图书馆,它很漂亮:

https://github.com/sindresorhus/multiline

之前

var str = '' +
'<!doctype html>' +
'<html>' +
'   <body>' +
'       <h1>❤ unicorns</h1>' +
'   </body>' +
'</html>' +
'';

之后

var str = multiline(function(){/*
<!doctype html>
<html>
    <body>
        <h1>❤ unicorns</h1>
    </body>
</html>
*/});

还要注意,当在每行末尾使用前向反斜杠在多行上扩展字符串时,前向反斜线后面的任何额外字符(主要是空格、制表符和错误添加的注释)都会导致意外的字符错误,我花了一个小时才发现

var string = "line1\  // comment, space or tabs here raise error
line2";

我想出了一个非常巧妙的方法来处理多行字符串。由于将函数转换为字符串也会返回函数内的任何注释,因此可以使用多行注释/**/将注释用作字符串。你只需要把两端修剪一下,你就有了你的绳子。

var myString = function(){/*
    This is some
    awesome multi-lined
    string using a comment 
    inside a function 
    returned as a string.
    Enjoy the jimmy rigged code.
*/}.toString().slice(14,-3)

alert(myString)

使用脚本标记:

添加<script></script>块,其中包含head标记中的多行文本;按原样获取多行文本…(注意文本编码:UTF-8、ASCII)<脚本>//纯javascriptvar text=document.getElementById(“mySoapMessage”).innerHTML;//使用JQuery的文档做好安全准备$(文档).ready(函数){var text=$(“#mySoapMessage”).html();});</script><script id=“mySoapMessage”type=“text/plain”><soapenv:Envelope xmlns:soapenv=“http://schemas.xmlsoap.org/soap/envelope/“xmlns:typ=”。。。"><soapenv:Header/><soapenv:Body><typ:getConvocatosElement>...</typ:getConvocatosElement></soapenv:Body></soapenv:信封><!-- 此注释将出现在字符串-->中//呃哦,javascript注释。。。SOAP请求将失败</script>