我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
当前回答
刚刚尝试了Anonymous的答案,发现这里有一个小技巧,如果反斜杠后面有空格,它就不起作用了因此,以下解决方案不起作用-
var x = { test:'<?xml version="1.0"?>\ <-- One space here
<?mso-application progid="Excel.Sheet"?>'
};
但当空间被移除时,它会起作用-
var x = { test:'<?xml version="1.0"?>\<-- No space here now
<?mso-application progid="Excel.Sheet"?>'
};
alert(x.test);
希望它有帮助!!
其他回答
我想出了一个非常巧妙的方法来处理多行字符串。由于将函数转换为字符串也会返回函数内的任何注释,因此可以使用多行注释/**/将注释用作字符串。你只需要把两端修剪一下,你就有了你的绳子。
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)
总之,我在用户javascript编程(Opera 11.01)中尝试了两种方法:
这一个不起作用:在JavaScript中创建多行字符串这非常有效,我还找到了如何让它在Notepad++源代码视图中看起来很好:在JavaScript中创建多行字符串
所以我推荐Opera用户JS用户的工作方法。与作者所说的不同:
它不适用于萤火虫或歌剧;仅在IE、chrome和safari上。
它在歌剧11中确实有效。至少在用户JS脚本中。遗憾的是,我不能对个人答案发表评论,也不能对答案进行投票,我会立即这样做。如果可能,请有更高权限的人帮我做。
我这样编程:
sys = {
layout: null,
makeLayout: function (obCLS) {
this.layout = $('<div />').addClass('editor').appendTo($(obCLS)).append(
/* Cargador */
/* @this.layout.find('> div:nth-of-child(1)'); */
'<div>' +
' <p>Seleccione la imagen que desea procesar.</p>' +
' <input type="button" value="Seleccionar" class="btn btn-xlarge btn-success" />' +
' <span></span>' +
'</div>' +
/* Cargador - Progreso */
/* @this.layout.find('> div:nth-of-child(2)'); */
'<div>' +
' <div>' +
' <div></div>' +
' <div>' +
' <div></div>' +
' </div>' +
' </div>' +
'</div>' +
/* Editor */
/* @this.layout.find('> div:nth-of-child(3)');
* @sidebar = this.layout.find('> div:nth-of-child(3) > div > div > div:nth-of-type(1)');
* @body = this.layout.find('> div:nth-of-child(3) > div > div > div:nth-of-type(2) > div'); */
'<div>' +
' <div>' +
' <div>' +
' <div></div>' +
' <div>' +
' <div></div>' +
' </div>' +
' </div>' +
' </div>' +
'</div>'
);
}
}
sys.makeLayout('#div');
准确的
Ruby produce:“This\nIs\nMultiline\nString\n”-在JS下面生成完全相同的字符串
text=`此是A.多行一串`//测试console.log(JSON.stringify(文本));console.log(文本);
这是对朗尼最佳答案的改进,因为他的答案中的换行符与ruby输出中的位置不完全相同
这适用于IE、Safari、Chrome和Firefox:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<div class="crazy_idea" thorn_in_my_side='<table border="0">
<tr>
<td ><span class="mlayouttablecellsdynamic">PACKAGE price $65.00</span></td>
</tr>
</table>'></div>
<script type="text/javascript">
alert($(".crazy_idea").attr("thorn_in_my_side"));
</script>