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

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

当前回答

在JavaScript中打印多行字符串的一种简单方法是使用由反引号(``)表示的模板文本(模板字符串)。还可以在模板字符串中使用变量,如(“name is${value}”)

你也可以

常量值=`multiline`const text=`这是一个${value}js中的字符串`;console.log(文本);

其他回答

您可以使用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

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

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)

我喜欢这种语法和含义:

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

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

ES6允许您使用反勾号在多行上指定字符串。它被称为模板文字。这样地:

var multilineString = `One line of text
    second line of text
    third line of text
    fourth line of text`;

在NodeJS中使用backtick,Chrome、Firefox、Edge、Safari和Opera都支持它。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

我想我发现了另一种方法,可以在没有任何侵入性语法的情况下,在每一行中内联执行。使用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