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

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

当前回答

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

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

也可以写成

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

console.log(hello);

其他回答

我喜欢这种语法和含义:

string = 'my long string...\n'
       + 'continue here\n'
       + 'and here.';

(但实际上不能视为多行字符串)

您可以使用TypeScript(JavaScript SuperSet),它支持多行字符串,并将文件向下转换为纯JavaScript而无需开销:

var templates = {
    myString: `this is
a multiline
string` 
}

alert(templates.myString);

如果您想用普通JavaScript实现同样的功能:

var templates = 
{
 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(templates.myString)

请注意,iPad/Safari不支持“functionName.toString()”

如果您有很多遗留代码,也可以在TypeScript中使用纯JavaScript变量(用于清理):

interface externTemplates
{
    myString:string;
}

declare var templates:externTemplates;

alert(templates.myString)

您可以使用普通JavaScript变体中的多行字符串对象,将模板放入另一个文件中(可以合并到捆绑包中)。

您可以在以下位置尝试TypeScripthttp://www.typescriptlang.org/Playground

我认为这个解决方法应该适用于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>

干杯

实现这一点有多种方法

1.斜线拼接

  var MultiLine=  '1\
    2\
    3\
    4\
    5\
    6\
    7\
    8\
    9';

2.规则串联

var MultiLine = '1'
+'2'
+'3'
+'4'
+'5';

3.数组连接串联

var MultiLine = [
'1',
'2',
'3',
'4',
'5'
].join('');

就性能而言,斜杠串联(第一个)是最快的。

有关性能的更多详细信息,请参阅本测试用例

更新:

使用ES2015,我们可以利用其模板字符串功能。有了它,我们只需要使用反引号来创建多行字符串

例子:

 `<h1>{{title}}</h1>
  <h2>{{hero.name}} details!</h2>
  <div><label>id: </label>{{hero.id}}</div>
  <div><label>name: </label>{{hero.name}}</div>
  `

出于对互联网的热爱,请使用字符串连接,并选择不使用ES6解决方案。ES6并不是全面支持的,很像CSS3,某些浏览器适应CSS3的移动速度很慢。使用简单的JavaScript,您的最终用户将感谢您。

例子:

var str=“这个世界既不是平的,也不是圆的。”+“一旦丢失将被发现”;