在JavaScript中创建多行字符串
我有以下Ruby代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么在JavaScript中创建多行字符串,javascript,string,multiline,heredoc,Javascript,String,Multiline,Heredoc,我有以下Ruby代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么 text = <<"HERE" This Is A Multiline String HERE text=您可以这样做 var string = 'This is\n' + 'a multiline\n' + 'string'; 更新: ECMAScript 6(ES6)引入了一种新的文本类型,即。它们有许多特性,变量插值等,但最重要的是,对于这个问题,它们可以是多行的
text = <<"HERE"
This
Is
A
Multiline
String
HERE
text=您可以这样做
var string = 'This is\n' +
'a multiline\n' +
'string';
更新:
ECMAScript 6(ES6)引入了一种新的文本类型,即。它们有许多特性,变量插值等,但最重要的是,对于这个问题,它们可以是多行的
模板文字由反勾号分隔:
const htmlString = `Say hello to
multi-line
strings!`;
模式text=在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>
警惕($(“.crazy_idea”).attr(“我身边的刺”);
您可以在纯JavaScript中使用多行字符串
此方法基于函数的序列化,即。它在大多数浏览器中都能工作(见下文),但不能保证它在将来仍能工作,所以不要依赖它
使用以下功能:
function hereDoc(f) {
return f.toString().
replace(/^[^\/]+\/\*!?/, '').
replace(/\*\/[^\/]+$/, '');
}
您可以在此处获得如下文档:
var tennysonQuote = hereDoc(function() {/*!
Theirs not to make reply,
Theirs not to reason why,
Theirs but to do and die
*/});
该方法已在以下浏览器中成功测试(未提及=未测试):
- IE 4-10
- 歌剧9.50-12(非9-)
- Safari 4-6(不在3-)
- 铬1-45
- Firefox 17-21()
- Rekonq 0.7.0-0.8.0
- Konqueror 4.7.4中不支持
不过要小心你的迷你们。它倾向于删除注释。对于,以/*开头的注释代码>(与我使用的代码一样)将被保留
我认为真正的解决办法是使用
ES6更新:您可以使用backtick,而不是创建带有注释的函数并在注释上运行toString。正则表达式只需要更新为带空间。您还可以使用字符串原型方法来执行此操作:
let foo = `
bar loves cake
baz loves beer
beer loves people
`.removeIndentation()
应该有人写这个。removeIndentation字符串方法…;) 总之,我尝试了用户javascript编程(Opera 11.01)中列出的两种方法:
- 这个没用:
- 这很有效,我还发现了如何在Notepad++源代码视图中使其看起来更好:
因此,我推荐Opera用户JS用户的工作方法。与作者所说的不同:
它在firefox或opera上不起作用;仅适用于IE、chrome和safari
它在歌剧11中确实起作用。至少在用户JS脚本中。太糟糕了,我不能对个人答案发表评论,也不能对答案投赞成票,我会立即这样做。如果可能,请具有更高权限的人为我执行此操作。ES6更新:
正如第一个答案所提到的,使用ES6/Babel,您现在可以简单地使用反勾号创建多行字符串:
const htmlString = `Say hello to
multi-line
strings!`;
内插变量是一项流行的新功能,它带有回勾分隔字符串:
const htmlString = `${user.name} liked your post about strings`;
这只是传递到串联:
user.name + ' liked your post about strings'
原ES5答案:
建议使用字符串连接而不是转义换行符:
不要这样做:
var myString = 'A rather long string of English text, an error message \
actually that just keeps going and going -- an error \
message to make the Energizer bunny blush (right through \
those Schwarzenegger shades)! Where was I? Oh yes, \
you\'ve got an error and all the extraneous whitespace is \
just gravy. Have a nice day.';
var myString = 'A rather long string of English text, an error message ' +
'actually that just keeps going and going -- an error ' +
'message to make the Energizer bunny blush (right through ' +
'those Schwarzenegger shades)! Where was I? Oh yes, ' +
'you\'ve got an error and all the extraneous whitespace is ' +
'just gravy. Have a nice day.';
<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>
每行开头的空白不能在编译时安全地去除;斜杠后的空格将导致棘手的错误;虽然大多数脚本引擎都支持这一点,但它不是ECMAScript的一部分
改用字符串连接:
var myString = 'A rather long string of English text, an error message \
actually that just keeps going and going -- an error \
message to make the Energizer bunny blush (right through \
those Schwarzenegger shades)! Where was I? Oh yes, \
you\'ve got an error and all the extraneous whitespace is \
just gravy. Have a nice day.';
var myString = 'A rather long string of English text, an error message ' +
'actually that just keeps going and going -- an error ' +
'message to make the Energizer bunny blush (right through ' +
'those Schwarzenegger shades)! Where was I? Oh yes, ' +
'you\'ve got an error and all the extraneous whitespace is ' +
'just gravy. Have a nice day.';
<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>
我喜欢这种语法和索引:
string = 'my long string...\n'
+ 'continue here\n'
+ 'and here.';
(但实际上不能被视为多行字符串)我很惊讶我没有看到这一点,因为它在我测试过的任何地方都能工作,并且对模板非常有用:
<script type="bogus" id="multi">
My
multiline
string
</script>
<script>
alert($('#multi').html());
</script>
我的
多行
一串
警报($('#multi').html());
有人知道有HTML但不起作用的环境吗?我通过输出一个div,将其隐藏,并在需要时通过jQuery调用div id来解决这个问题
e、 g
它以多行形式返回我的文本。如果我打电话
alert($('#UniqueID').html());
我得到:
使用脚本标记:
- 将包含多行文本的
..
块添加到标题
标记中李>
- 按原样获取多行文本。。。(注意文本编码:UTF-8,ASCII)
//纯javascript
var text=document.getElementById(“mySoapMessage”).innerHTML;
//使用JQuery的文档为安全做好准备
$(文档).ready(函数(){
var text=$(“#mySoapMessage”).html();
});
...
//哦,javascript评论。。。SOAP请求将失败
我认为这种解决方法应该适用于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>
一些纯文本
两种类型的引号:“'”和“'”
JS代码:警报(“你好世界”);
HTML代码:
警报($('#unique_id').html());
使用纯Javascript:
var myString = 'A rather long string of English text, an error message \
actually that just keeps going and going -- an error \
message to make the Energizer bunny blush (right through \
those Schwarzenegger shades)! Where was I? Oh yes, \
you\'ve got an error and all the extraneous whitespace is \
just gravy. Have a nice day.';
var myString = 'A rather long string of English text, an error message ' +
'actually that just keeps going and going -- an error ' +
'message to make the Energizer bunny blush (right through ' +
'those Schwarzenegger shades)! Where was I? Oh yes, ' +
'you\'ve got an error and all the extraneous whitespace is ' +
'just gravy. Have a nice day.';
<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>
一些纯文本
两种类型的引号:“'”和“'”
JS代码:警报(“你好世界”);
HTML代码:
警报(document.getElementById('unique_id').innerHTML);
干杯 下选按钮:此代码仅供参考
这已经在Mac上的FX19和Chrome 24中进行了测试
var新注释/* 我想出了一个非常吉米操纵的方法,一条多线的绳子。由于将函数转换为字符串也会返回函数内的任何注释,因此可以使用多行注释/**/将注释用作字符串。你只需要把两端剪掉,你就有了你的绳子
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)
字符串concat的基于数组的联接的我的版本:
var c = []; //c stands for content
c.push("<div id='thisDiv' style='left:10px'></div>");
c.push("<div onclick='showDo(\'something\');'></div>");
$(body).append(c.join('\n'));
var c=[]//c代表内容
c、 推动(“”);
c、 推动(“”);
$(body).append(c.join('\n'));
这对我来说效果很好,特别是我经常用这种方式在html中插入值。但它有很多局限性。那就好了。不必处理嵌套的引号会非常好,只是它的笨重让我感到困扰
要添加到数组中的.push()是否占用大量时间?请参阅以下相关答案:
()
在查看这些(相反的)测试运行之后,看起来.push()是
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)
var c = []; //c stands for content
c.push("<div id='thisDiv' style='left:10px'></div>");
c.push("<div onclick='showDo(\'something\');'></div>");
$(body).append(c.join('\n'));
Function.prototype.extractComment = function() {
var startComment = "/*!";
var endComment = "*/";
var str = this.toString();
var start = str.indexOf(startComment);
var end = str.lastIndexOf(endComment);
return str.slice(start + startComment.length, -(str.length - end));
};
var tmpl = function() { /*!
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
</ul>
</div>
*/}.extractComment();
var hello = 'hello' +
'world' +
'blah';
var hello = 'hello';
hello += ' world';
hello += ' blah';
console.log(hello);
var template = require('text!template.html')
var fs = require("fs");
var template = fs.readFileSync(template.html', 'utf8');
var str = '' +
'<!doctype html>' +
'<html>' +
' <body>' +
' <h1>❤ unicorns</h1>' +
' </body>' +
'</html>' +
'';
var str = multiline(function(){/*
<!doctype html>
<html>
<body>
<h1>❤ unicorns</h1>
</body>
</html>
*/});
var MultiLine= '1\
2\
3\
4\
5\
6\
7\
8\
9';
var MultiLine = '1'
+'2'
+'3'
+'4'
+'5';
var MultiLine = [
'1',
'2',
'3',
'4',
'5'
].join('');
`<h1>{{title}}</h1>
<h2>{{hero.name}} details!</h2>
<div><label>id: </label>{{hero.id}}</div>
<div><label>name: </label>{{hero.name}}</div>
`
var templates = {
myString: `this is
a multiline
string`
}
alert(templates.myString);
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)
interface externTemplates
{
myString:string;
}
declare var templates:externTemplates;
alert(templates.myString)
var text = `
This
Is
A
Multiline
String
`;
var multilineString = `One line of text
second line of text
third line of text
fourth line of text`;
var string = "line1\ // comment, space or tabs here raise error
line2";
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<p id="demo"></p>
<script>
var str = "This "
+ "\n<br>is "
+ "\n<br>multiline "
+ "\n<br>string.";
document.getElementById("demo").innerHTML = str;
</script>
</body>
</html>
This
<br>is
<br>multiline
<br>string.
This
is
multiline
string.
const str = `This
is
a
multiline text`;
console.log(str);
// 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'