我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
当前回答
您可以使用标记的模板来确保获得所需的输出。
例如:
// Merging multiple whitespaces and trimming the output
const t = (strings) => { return strings.map((s) => s.replace(/\s+/g, ' ')).join("").trim() }
console.log(t`
This
Is
A
Multiline
String
`);
// Output: 'This Is A Multiline String'
// Similar but keeping whitespaces:
const tW = (strings) => { return strings.map((s) => s.replace(/\s+/g, '\n')).join("").trim() }
console.log(tW`
This
Is
A
Multiline
String
`);
// Output: 'This\nIs\nA\nMultiline\nString'
其他回答
实现这一点有多种方法
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>
`
还要注意,当在每行末尾使用前向反斜杠在多行上扩展字符串时,前向反斜线后面的任何额外字符(主要是空格、制表符和错误添加的注释)都会导致意外的字符错误,我花了一个小时才发现
var string = "line1\ // comment, space or tabs here raise error
line2";
使用脚本标记:
添加<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>
准确的
Ruby produce:“This\nIs\nMultiline\nString\n”-在JS下面生成完全相同的字符串
text=`此是A.多行一串`//测试console.log(JSON.stringify(文本));console.log(文本);
这是对朗尼最佳答案的改进,因为他的答案中的换行符与ruby输出中的位置不完全相同
带变量的多行字符串
var x = 1
string = string + `<label class="container">
<p>${x}</p>
</label>`;