简体   繁体   English

如何打破一个字符串,使其不在我的源代码中的一行中?

[英]How to break a string so it is not all in one line in my source code?

say I have the following string in javascript:假设我在 javascript 中有以下字符串:

const myStr = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididuntut labore et dolore magna aliqua. Vel facilisis volutpat est velit. Enim nunc faucibus a pellentesque sit." but everytime I try to break it so it occupies two lines in atom so I can see it all, it is not one string anymore.但每次我试图打破它,让它在原子中占据两行,所以我可以看到它,它不再是一个字符串了。 How can I do it properly?我怎样才能正确地做到这一点?

Depending on how it is used, you can use javascript template strings or just concatenate.根据它的使用方式,您可以使用 javascript 模板字符串或只是连接。

To use template strings, you simply wrap your text in backticks.要使用模板字符串,您只需将文本包装在反引号中。 This also gives the added benefit of allowing string interpolation with variables.这也带来了允许使用变量进行字符串插值的额外好处。 The only downside is that it will preserve white space.唯一的缺点是它会保留空白。

Eg:例如:

const name = 'Jen';
const myLongStr = `Hello ${name}, This is a super long string that
    needs to break between lines. It's not that big of an issue
    depending on the use case.`
const strWithHtml = `<p>Hello <strong>${name}</strong>,</p>
                     <p>This is a paragraph, demostrating HTML usage.</p>`

The other option, as mentioned in other answers is simple string concatenation.正如其他答案中提到的,另一个选项是简单的字符串连接。

Eg:例如:

const myLongStr = 'Lorem ipsum dolor sit amet, consectetur ' +
                  'adipiscing elit, sed do eiusmod tempor incididuntut ' +
                  'labore et dolore magna aliqua. Vel facilisis volutpat ' +
                  'est velit. Enim nunc faucibus a pellentesque sit.';

Depending on your use case, choosing one of these should work well.根据您的用例,选择其中之一应该会很好。

Due to Javascript allowing you to break things onto multiple lines as long as a line doesn't end with a semicolon, this becomes quite easy.由于 Javascript 允许您将内容分成多行,只要一行不以分号结尾,这变得非常容易。

const myStr = "Lorem ipsum dolor sit amet, consectetur "
 + "adipiscing elit, sed do eiusmod tempor incididuntut"
 + "labore et dolore magna aliqua. Vel facilisis volutpat"
 + "est velit. Enim nunc faucibus a pellentesque sit."

Mean something like this?意思是这样的?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM