我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
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
其他回答
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
在Javascrip中创建多行字符串最简单的方法是使用反引号(``)。这允许您创建多行字符串,在其中可以插入带有${variableName}的变量。
例子:
let name='Willem';假设年龄=26岁;让multilineString=`我的名字是:${name}我的年龄是:${age}`;console.log(multilineString);
兼容性:
它在ES6//es2015中介绍现在,所有主要浏览器供应商(internet explorer除外)都支持它
在此处查看Mozilla文档中的确切兼容性
如果您愿意使用转义换行符,它们可以很好地使用。它看起来像带有页面边框的文档。
你可以这样做。。。
var string = 'This is\n' +
'a multiline\n' +
'string';
准确的
Ruby produce:“This\nIs\nMultiline\nString\n”-在JS下面生成完全相同的字符串
text=`此是A.多行一串`//测试console.log(JSON.stringify(文本));console.log(文本);
这是对朗尼最佳答案的改进,因为他的答案中的换行符与ruby输出中的位置不完全相同