提问人:Newy 提问时间:4/30/2009 最后编辑:Ryan MNewy 更新时间:11/4/2022 访问量:2304591
在 JavaScript 中创建多行字符串
Creating multiline strings in JavaScript
问:
我在Ruby中有以下代码。我想将这段代码转换为 JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
答:
你可以这样做...
var string = 'This is\n' +
'a multiline\n' +
'string';
评论
更新:
ECMAScript 6 (ES6) 引入了一种新型的文字,即模板文字。它们具有许多特征,可变插值等,但最重要的是,对于这个问题,它们可以是多行的。
模板文本由反引号分隔:
var html = `
<div>
<span>Some HTML here</span>
</div>
`;
(注意:我不提倡在字符串中使用 HTML)
原 ES5 答案:
Javascript 没有 here-document 语法。但是,您可以转义文字换行符,它接近:
"foo \
bar"
评论
该模式在 js 中不可用(我记得在我过去的 Perl 时代经常使用它)。text = <<"HERE" This Is A Multiline String HERE
为了保持对复杂或长多行字符串的监督,我有时会使用数组模式:
var myString =
['<div id="someId">',
'some content<br />',
'<a href="#someRef">someRefTxt</a>',
'</div>'
].join('\n');
或者 Anonymous 已经显示的模式(转义换行符),这可能是代码中一个丑陋的块:
var myString =
'<div id="someId"> \
some content<br /> \
<a href="#someRef">someRefTxt</a> \
</div>';
这是另一个奇怪但有效的“技巧”1:
var myString = (function () {/*
<div id="someId">
some content<br />
<a href="#someRef">someRefTxt</a>
</div>
*/}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];
外部编辑:JSFiddle
ES20xx 支持使用模板字符串跨越多行字符串:
let str = `This is a text
with multiple lines.
Escapes are interpreted,
\n is a newline.`;
let str = String.raw`This is a text
with multiple lines.
Escapes are not interpreted,
\n is not a newline.`;
1 注意:在缩小/混淆代码后,这将丢失
评论
这适用于 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>
评论
'
'
您可以在纯 JavaScript 中使用多行字符串。
此方法基于函数的序列化,该序列化被定义为与实现相关。它确实适用于大多数浏览器(见下文),但不能保证它将来仍然有效,所以不要依赖它。
使用以下函数:
function hereDoc(f) {
return f.toString().
replace(/^[^\/]+\/\*!?/, '').
replace(/\*\/[^\/]+$/, '');
}
你可以有这样的 here-documents:
var tennysonQuote = hereDoc(function() {/*!
Theirs not to make reply,
Theirs not to reason why,
Theirs but to do and die
*/});
The method has successfully been tested in the following browsers (not mentioned = not tested):
- IE 4 - 10
- Opera 9.50 - 12 (not in 9-)
- Safari 4 - 6 (not in 3-)
- Chrome 1 - 45
- Firefox 17 - 21 (not in 16-)
- Rekonq 0.7.0 - 0.8.0
- Not supported in Konqueror 4.7.4
Be careful with your minifier, though. It tends to remove comments. For the YUI compressor, a comment starting with (like the one I used) will be preserved./*!
I think a real solution would be to use CoffeeScript.
ES6 UPDATE: You could use backtick instead of creating a function with a comment and running toString on the comment. The regex would need to be updated to only strip spaces. You could also have a string prototype method for doing this:
let foo = `
bar loves cake
baz loves beer
beer loves people
`.removeIndentation()
Someone should write this .removeIndentation string method... ;)
评论
to sum up, I have tried 2 approaches listed here in user javascript programming (Opera 11.01):
- this one didn't work: Creating multiline strings in JavaScript
- this worked fairly well, I have also figured out how to make it look good in Notepad++ source view: Creating multiline strings in JavaScript
So I recommend the working approach for Opera user JS users. Unlike what the author was saying:
It doesn't work on firefox or opera; only on IE, chrome and safari.
It DOES work in Opera 11. At least in user JS scripts. Too bad I can't comment on individual answers or upvote the answer, I'd do it immediately. If possible, someone with higher privileges please do it for me.
评论
ES6 Update:
As the first answer mentions, with ES6/Babel, you can now create multi-line strings simply by using backticks:
const htmlString = `Say hello to
multi-line
strings!`;
Interpolating variables is a popular new feature that comes with back-tick delimited strings:
const htmlString = `${user.name} liked your post about strings`;
This just transpiles down to concatenation:
user.name + ' liked your post about strings'
Original ES5 answer:
Google's JavaScript style guide recommends to use string concatenation instead of escaping newlines:
Do not do this:
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.';
The whitespace at the beginning of each line can't be safely stripped at compile time; whitespace after the slash will result in tricky errors; and while most script engines support this, it is not part of ECMAScript.
Use string concatenation instead:
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.';
评论
\
I like this syntax and indendation:
string = 'my long string...\n'
+ 'continue here\n'
+ 'and here.';
(but actually can't be considered as multiline string)
评论
I'm surprised I didn't see this, because it works everywhere I've tested it and is very useful for e.g. templates:
<script type="bogus" id="multi">
My
multiline
string
</script>
<script>
alert($('#multi').html());
</script>
Does anybody know of an environment where there is HTML but it doesn't work?
评论
I solved this by outputting a div, making it hidden, and calling the div id by jQuery when I needed it.
e.g.
<div id="UniqueID" style="display:none;">
Strings
On
Multiple
Lines
Here
</div>
Then when I need to get the string, I just use the following jQuery:
$('#UniqueID').html();
Which returns my text on multiple lines. If I call
alert($('#UniqueID').html());
I get:
评论
display:none
Using script tags:
- add a block containing your multiline text into tag;
<script>...</script>
head
get your multiline text as is... (watch out for text encoding: UTF-8, ASCII)
<script> // pure javascript var text = document.getElementById("mySoapMessage").innerHTML ; // using JQuery's document ready for safety $(document).ready(function() { 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:getConvocadosElement> ... </typ:getConvocadosElement> </soapenv:Body> </soapenv:Envelope> <!-- this comment will be present on your string --> //uh-oh, javascript comments... SOAP request will fail </script>
评论
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
Just tried the Anonymous answer and found there's a little trick here, it doesn't work if there's a space after backslash
So the following solution doesn't work -\
var x = { test:'<?xml version="1.0"?>\ <-- One space here
<?mso-application progid="Excel.Sheet"?>'
};
But when space is removed it works -
var x = { test:'<?xml version="1.0"?>\<-- No space here now
<?mso-application progid="Excel.Sheet"?>'
};
alert(x.test);
Hope it helps !!
评论
I think this workaround should work in IE, Chrome, Firefox, Safari, Opera -
Using 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>
Using Pure Javascript :
<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>
Cheers!!
评论
<xmp>
is so deprecated. It may be allowed in HTML, but should not be used by any authors. See stackoverflow.com/questions/8307846/…
<pre>;
style="display:none"
<img>
Downvoters: This code is supplied for information only.
This has been tested in Fx 19 and Chrome 24 on Mac
var new_comment; /*<<<EOF
<li class="photobooth-comment">
<span class="username">
<a href="#">You</a>:
</span>
<span class="comment-text">
$text
</span>
@<span class="comment-time">
2d
</span> ago
</li>
EOF*/
// note the script tag here is hardcoded as the FIRST tag
new_comment=document.currentScript.innerHTML.split("EOF")[1];
document.querySelector("ul").innerHTML=new_comment.replace('$text','This is a dynamically created text');
<ul></ul>
评论
It's not extremely elegant but it's clean enough for me:
var myString = "First line" + "\n";
var myString = myString + "Second line" + "\n";
var myString = myString + "Third line" + "\n";
评论
var myString += "Second line \n";
myString += "Second line \n";
var
This is one fairly economical approach, at least in terms of the source code:
function s() {
var args = [],index;
for (index = 0; index< arguments.length; index++) {
args.push (arguments [index]);
}
return args.join ("\n");
}
console.log (s (
"This is the first line",
"and this is the second",
"finally a third"
));
function s() {return arguments.join ("\n")}
would be nicer of course if the "arguments" property were a proper array.
A second version might use "" to do the join for cases when you want to control the line breaks in a very long string.
评论
function s() { return Array.prototype.join.call(arguments, '\n'); }
I came up with this very jimmy rigged method of a multi lined string. Since converting a function into a string also returns any comments inside the function you can use the comments as your string using a multilined comment /**/. You just have to trim off the ends and you have your string.
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)
评论
toString()
I program this way:
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');
评论
I think I discovered another way to do it inline without any invasive syntax on every line. Use Javascript's ability to convert a function to string and create a multiline comment with the syntax then remove the "function() {/*\n" and "\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!
*/}));
The only pitfall I can see in this is the syntax highlighting.
EDIT: Had I scrolled down a little more, I would have seen this answer doing exactly the same thing: https://stackoverflow.com/a/5571069/916553
My version of array-based join for string 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'));
This has worked well for me, especially as I often insert values into the html constructed this way. But it has lots of limitations. Indentation would be nice. Not having to deal with nested quotation marks would be really nice, and just the bulkyness of it bothers me.
Is the .push() to add to the array taking up a lot of time? See this related answer:
(Is there a reason JavaScript developers don't use Array.push()?)
After looking at these (opposing) test runs, it looks like .push() is fine for string arrays which will not likely grow over 100 items - I will avoid it in favor of indexed adds for larger arrays.
i found a more elegant solution, maybe a little non-topic related because it uses PHP, but im sure it will be useful and cuteness* for some of yours...
this javascript code should stay inside script tags
var html=<?php echo json_encode("
<div class=container>
<div class=area1>
xxx
</div>
<div class=area2>
".$someVar."
</div>
</div>
"); ?>
in your output html you will see something like
var html="\r\n\r\n\t\t\t<div class=container>\r\n\t\t\t\t<div class=area1>\r\n\t\t\t\t\txxx\r\n\t\t\t\t<\/div>\r\n\t\t\t\t<div class=area2>\r\n\t\t\t\t\t44\r\n\t\t\t\t<\/div>\r\n\t\t\t<\/div>\r\n\r\n\t\t";
and et voilà!, it gives you code readability in your file.
pD: this sample uses json_encode() PHP function, but certainly there are function equivalents for ASP, Ruby and JSP langs.
pD: however, this solution have his limitations too, one of them is you cannot use javascript variables inside the encapsulated code.
评论
My extension to https://stackoverflow.com/a/15558082/80404.
It expects comment in a form where symbol ! is used to prevent removing by minification (at least for YUI compressor)/*! any multiline comment */
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));
};
Example:
var tmpl = function() { /*!
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
</ul>
</div>
*/}.extractComment();
You can use to concatenate your string, seems like no one answered that, which will be readable, and also neat... something like this+=
var hello = 'hello' +
'world' +
'blah';
can be also written as
var hello = 'hello';
hello += ' world';
hello += ' blah';
console.log(hello);
Updated for 2015: it's six years later now: most people use a module loader, and the main module systems each have ways of loading templates. It's not inline, but the most common type of multiline string are templates, and templates should generally be kept out of JS anyway.
require.js: 'require text'.
Using require.js 'text' plugin, with a multiline template in template.html
var template = require('text!template.html')
NPM/browserify: the 'brfs' module
Browserify uses a 'brfs' module to load text files. This will actually build your template into your bundled HTML.
var fs = require("fs");
var template = fs.readFileSync(template.html', 'utf8');
Easy.
There's this library that makes it beautiful:
https://github.com/sindresorhus/multiline
Before
var str = '' +
'<!doctype html>' +
'<html>' +
' <body>' +
' <h1>❤ unicorns</h1>' +
' </body>' +
'</html>' +
'';
后
var str = multiline(function(){/*
<!doctype html>
<html>
<body>
<h1>❤ unicorns</h1>
</body>
</html>
*/});
评论
nodejs
Function.prototype.String()
有多种方法可以实现此目的
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>
`
评论
如果你碰巧只在 Node 中运行,你可以使用 fs 模块从文件中读入多行字符串:
var diagram;
var fs = require('fs');
fs.readFile( __dirname + '/diagram.txt', function (err, data) {
if (err) {
throw err;
}
diagram = data.toString();
});
如果您愿意使用转义换行符,则可以很好地使用它们。它看起来像一个带有页面边框的文档。
评论
你可以使用 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 变体中的多行字符串对象,将模板放入另一个文件(您可以将其合并到捆绑包中)。
您可以在 http://www.typescriptlang.org/Playground 试用
TypeScript
评论
javascript 中的等价物是:
var text = `
This
Is
A
Multiline
String
`;
ES6 允许您使用反引号在多行上指定字符串。它称为模板文本。喜欢这个:
var multilineString = `One line of text
second line of text
third line of text
fourth line of text`;
使用反引号适用于 NodeJS,Chrome、Firefox、Edge、Safari 和 Opera 都支持它。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
还要注意的是,当在每行末尾使用正反斜杠将字符串扩展到多行时,正反斜杠后的任何额外字符(主要是空格、制表符和错误添加的注释)都会导致意外的字符错误,我花了一个小时才发现
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>
通过使用您的源代码将如下所示 -\n
This <br>is <br>multiline <br>string.
通过使用浏览器,输出将如下所示 -<br>
This is multiline string.
出于对互联网的热爱,请使用字符串连接,并选择不使用 ES6 解决方案。ES6 并非全面支持,就像 CSS3 和某些浏览器适应 CSS3 运动的速度很慢一样。使用普通的 JavaScript,您的最终用户会感谢您。
例:
var str = "This world is neither flat nor round. "+
"Once was lost will be found";
评论
ES6 的方法是使用模板文字:
const str = `This
is
a
multiline text`;
console.log(str);
更多参考资料在这里
评论
在 Javascrips 中制作多行字符串的最简单方法是使用反引号 ( '' )。这允许您创建多行字符串,您可以在其中插入带有 .${variableName}
例:
let name = 'Willem';
let age = 26;
let multilineString = `
my name is: ${name}
my age is: ${age}
`;
console.log(multilineString);
兼容性:
- 它被介绍在
ES6
//es2015
- 现在,所有主要浏览器供应商(Internet Explorer 除外)都原生支持它
评论
规则是:在字符串内时,在需要换行符的任何位置使用 \n;你不必在\n之前或之后加一个空格,JavaScript的解释器足够聪明,知道不可打印的字符表示有多长。
确切
Ruby 产生: - 下面的 JS 产生完全相同的字符串"This\nIs\nA\nMultiline\nString\n"
text = `This
Is
A
Multiline
String
`
// TEST
console.log(JSON.stringify(text));
console.log(text);
这是对 Lonnie Best 答案的改进,因为他的答案中的换行符与 ruby 输出中的位置并不完全相同
评论
\n
您可以使用标记模板来确保获得所需的输出。
例如:
// 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'
JavaScript 从来没有一个真正好的方法来处理多行字符串,直到 2015 年引入了 ES6 以及模板文字。
模板文字是由反引号('')分隔的字符串,而不是普通的single('')/doublebl(“”)e引号分隔符。
评论
在这里找到了很多过度设计的答案。 在我看来,最好的两个答案是:
1:
let str = `Multiline string.
foo.
bar.`
最终记录:
Multiline string.
foo.
bar.
2:
let str = `Multiline string.
foo.
bar.`
这正确地记录了它,但如果 str 嵌套在函数/对象等中,它在脚本文件中是丑陋的......
Multiline string.
foo.
bar.
我对正则表达式的非常简单的答案,它正确记录了 str:
let str = `Multiline string.
foo.
bar.`.replace(/\n +/g, '\n');
请注意,这不是完美的解决方案,但如果您确定在新行 (\n) 之后至少会出现一个空格(+ 表示至少出现一次),它就会起作用。它也可以与 *(零或更多)一起使用。
您可以更明确地使用 {n,},这意味着至少出现 n 次。
评论
[ "line", "line2", "line3" ].join("\n")
带变量的多行字符串
var x = 1
string = string + `<label class="container">
<p>${x}</p>
</label>`;
在 JavaScript 中打印多行字符串的一种简单方法是使用由反引号 (' ') 表示的模板文字(模板字符串)。您还可以在模板中使用类似字符串的变量('name is ${value}
`)
您还可以
const value = `multiline`
const text = `This is a
${value}
string in js`;
console.log(text);
评论