在 JavaScript 中创建多行字符串
2022-08-29 21:46:27
我在Ruby中有以下代码。我想将此代码转换为JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
我在Ruby中有以下代码。我想将此代码转换为JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
正如第一个答案所提到的,使用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'
Google 的 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.';
每行开头的空格在编译时无法安全剥离;斜杠后的空格会导致棘手的错误;虽然大多数脚本引擎都支持此功能,但它不是 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.';