如何将多行字符串字面量赋值给变量

如何将多行字符串字面量赋值给变量

技术背景

在JavaScript编程中,有时候需要处理多行字符串,比如HTML模板、大段文本等。然而,JavaScript本身在早期版本中并没有方便的多行字符串处理方式,随着版本的发展,逐渐有了多种解决方案。

实现步骤

ES6及以后版本(模板字面量)

ECMAScript 6(ES6)引入了模板字面量(Template Literals),它使用反引号(`)来界定字符串,可以轻松实现多行字符串。

1
2
3
4
5
const html = `
<div>
<span>Some HTML here</span>
</div>
`;

ES5及以前版本

  • 转义换行符:可以通过在每行末尾使用反斜杠(\)来转义换行符,达到多行字符串的效果。
1
2
3
4
5
6
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.';

不过,这种方式有一些缺点,比如行首的空格不能在编译时安全地去除,反斜杠后的空格可能会导致难以调试的错误,并且它不是ECMAScript标准的一部分。

  • 字符串拼接:使用加号(+)进行字符串拼接。
1
2
3
4
5
6
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.';
  • 数组拼接:将每行字符串存储在数组中,然后使用join方法拼接成一个字符串。
1
2
3
4
5
6
var myString = [
'<div id="someId">',
'some content<br />',
'<a href="#someRef">someRefTxt</a>',
'</div>'
].join('\n');

其他方法

  • 函数注释法:利用函数的注释来存储多行字符串。
1
2
3
4
5
6
7
8
9
10
11
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
*/});
  • HTML标签法:使用<script>标签存储多行字符串。
1
2
3
4
5
6
7
8
9
10
11
12
13
<script type="text/plain" id="mySoapMessage">
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:typ="...">
<soapenv:Header/>
<soapenv:Body>
<typ:getConvocadosElement>
...
</typ:getConvocadosElement>
</soapenv:Body>
</soapenv:Envelope>
</script>
<script>
var text = document.getElementById("mySoapMessage").innerHTML;
</script>

核心代码

模板字面量示例

1
2
3
4
const str = `This is a text
with multiple lines.
Escapes are interpreted,
\n is a newline.`;

字符串拼接示例

1
2
3
var string = 'This is\n' +
'a multiline\n' +
'string';

数组拼接示例

1
2
3
4
5
6
7
var MultiLine = [
'1',
'2',
'3',
'4',
'5'
].join('');

最佳实践

  • 优先使用模板字面量:如果项目支持ES6及以上版本,优先使用模板字面量,因为它语法简洁,并且支持变量插值。
  • 注意兼容性:如果需要兼容旧版本浏览器,可以使用转译工具(如Babel)将ES6代码转换为ES5代码。
  • 避免使用复杂的方法:尽量避免使用函数注释法等复杂的方法,除非有特殊需求。

常见问题

  • 转义换行符的问题:转义换行符时,行首的空格和反斜杠后的空格可能会导致错误,需要特别注意。
  • 函数注释法的局限性:函数注释法在代码压缩和混淆后可能会失效,因为注释可能会被移除。
  • HTML标签法的编码问题:使用HTML标签存储字符串时,需要注意文本编码,确保字符串的正确性。

如何将多行字符串字面量赋值给变量
https://119291.xyz/posts/2025-05-09.how-to-assign-multiline-string-literal-to-variable/
作者
ww
发布于
2025年5月9日
许可协议