Javascript 模板字符串 ES6 防止换行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38000659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:58:02  来源:igfitidea点击:

Template Strings ES6 prevent line breaks

javascriptecmascript-6template-strings

提问by dim0_0n

I have a long string, which I build using ES6 template strings, but I want it to be without line breaks:

我有一个很长的字符串,我使用 ES6 模板字符串构建它,但我希望它没有换行符:

var string = `As all string substitutions in Template Strings are JavaScript
              expressions, we can substitute a lot more than variable names.
              For example, below we can use expression interpolation to 
              embed for some readable inline math:`

console.log(string);

Result:

结果:

As all string substitutions in Template Strings are JavaScript
expressions, we can substitute a lot more than variable names.
For example, below we can use expression interpolation to
embed for some readable inline math:

My expectations:

我的期望:

As all string substitutions in Template Strings are JavaScript expressions, we can substitute a lot more than variable names. For example, below we can use expression interpolation to embed for some readable inline math:

回答by Cyril CHAPON

This is insane.

疯了吧。

Almost every single answer here suggest running a function runtimein order to well-format, buildtimebad-formatted text oO Am I the only one shocked by that fact, especially performance impact ???

几乎这里的每一个答案都建议运行一个函数运行时来格式化、构建时格式错误的文本 oO 我是唯一一个被这一事实震惊的人吗,尤其是对性能的影响???

As stated by @dandavis, the official solution, (which btw is also the historic solution for unix shell scripts), is to escape the carriage return, well, with the escape character : \

正如@dandavis 所述,官方解决方案(顺便说一句,这也是 unix shell 脚本的历史解决方案)是使用转义字符转义回车符:\

`foo \
bar` === 'foo bar'

Simple, performant, official, readable, and shell-like in the process

过程中简单、高效、官方、可读、类shell

回答by Matías Fidemraizer

A line break is a line break... If you produce them manually, I find very expectable that you get them during run-time.

换行符就是换行符...如果您手动生成它们,我发现您在运行时获得它们是非常值得期待的。

BTW, I find three workarounds for now:

顺便说一句,我现在找到了三个解决方法:

  1. Configure your IDE or code editor to do word wrap so you won't need to add line breaks in your code if you don't need them: your editor will break your code in two or more lines if each code sentence goes beyond configured maximum characters.

  2. Remove line breaks with String.prototype.replace:

  1. 将您的 IDE 或代码编辑器配置为自动换行,这样您就无需在不需要的情况下在代码中添加换行符:如果每个代码句超出配置的最大值,您的编辑器会将代码分成两行或更多行人物。

  2. 删除换行符String.prototype.replace

var string = `As all string substitutions in Template Strings are JavaScript
expressions, we can substitute a lot more than variable names.
For example, below we can use expression interpolation to
embed for some readable inline math:`.replace(/\n/gm,"");

Caution: here you're running a function runtimeto format your buildtimecode, which might look like an anti-pattern, and have performance impact

注意:这里你正在运行一个函数运行时来格式化你的构建时代码,这可能看起来像一个反模式,并且会影响性​​能

  1. Perform these code line breaks using concatenations:
  1. 使用串联执行这些代码换行符:
var string = `As all string substitutions in Template Strings are JavaScript`
              + `expressions, we can substitute a lot more than variable names.`
              + `For example, below we can use expression interpolation to` 
              + `embed for some readable inline math:`;

In my case, I would go with #1 option.

就我而言,我会选择 #1 选项。

回答by kvz

If you have ES6, you can use tags. For instance, the stripIndent tag from the common-tags library:

如果你有 ES6,你可以使用标签。例如,来自 common-tags 库的 stripIndent 标签

Install via:

通过以下方式安装:

npm install common-tags --save

Require via:

要求通过:

const stripIndent = require('common-tags/lib/stripIndent')

Use as:

用于:

stripIndent`
  As all string substitutions in Template Strings are JavaScript
  expressions, we can substitute a lot more than variable names.
  For example, below we can use expression interpolation to
  embed for some readable inline math:        
`

Edit:As mentioned in the comments, you likely need to pick the: const oneLine = require('common-tags/lib/oneLine')tag for your desired outcome.

编辑:如评论中所述,您可能需要const oneLine = require('common-tags/lib/oneLine')为您想要的结果选择:标签。

More info on the aforementioned common-tags link as well as on this blog

有关上述通用标签链接以及此博客的更多信息

回答by jaybee

I personally prefer the look of joining an array instead:

我个人更喜欢加入数组的外观:

var string = [
  `As all string substitutions in Template Strings are JavaScript`,
  `expressions, we can substitute a lot more than variable names.`,
  `For example, below we can use expression interpolation to`,
  `embed for some readable inline math:`
].join(' ');

回答by Eugene Mihaylin

  • Either configure IDE to make wraps and use template string 1-liner, as in your 1st code snippet.

  • Either use \escape literal char just before the line breaks.

    Example:

    const string = `1st line\
    2nd line\ 
    3rd line`; 
    

    But it will not save you from issues with space-aligning.

  • Either use old-school ES5 concatenation with '+'.

    Example:

    const string = '1st line' + 
                   '2nd line' + 
                   '3rd line'; 
    
  • Either use hack with template empty string var ${''}:

    Example:

    const string = `1st line${'' 
                   }2nd line${'' 
                   }3rd line`;
    
  • 配置 IDE 以进行包装并使用模板字符串 1-liner,如您的第一个代码片段。

  • 要么\在换行符之前使用转义文字字符。

    例子:

    const string = `1st line\
    2nd line\ 
    3rd line`; 
    

    但它不会使您免于空间对齐的问题。

  • 要么使用带有“+”的老式 ES5 连接。

    例子:

    const string = '1st line' + 
                   '2nd line' + 
                   '3rd line'; 
    
  • 要么使用带有模板空字符串 var ${''} 的 hack:

    例子:

    const string = `1st line${'' 
                   }2nd line${'' 
                   }3rd line`;
    

The 1st way is much more better, cause:

第一种方法要好得多,原因是:

  • less symbols (size aspect)
  • no runtime operations (perfomance aspect)
  • 更少的符号(大小方面)
  • 没有运行时操作(性能方面)

回答by L. Holanda

For paragraphs, you can use the \s+regex to replace white space runs with a single space so it will work for line breaks as well as the indentations. So, in your case, just add .replace(/\s+/gm, ' ')at the end.

对于段落,您可以使用\s+正则表达式将空白行替换为单个空格,以便它适用于换行符和缩进。所以,在你的情况下,只需.replace(/\s+/gm, ' ')在最后添加。

var string = `As all string substitutions in Template Strings are JavaScript
              expressions, we can substitute a lot more than variable names.
              For example, below we can use expression interpolation to 
              embed for some readable inline math:`.replace(/\s+/gm, ' ');

console.log(string);

回答by mdawsondev

In ES6, I prefer using a combination of the two top answers here (\in combination with .replace()). The benefit of combining the replace function with the escape character means you can keep your codeblock consistently formatted with the rest of your code.

在 ES6 中,我更喜欢在此处\结合使用两个最佳答案(与 结合使用.replace())。将替换函数与转义符结合的好处意味着您可以使代码块与其余代码的格式保持一致。

/\s{2}/gis a regular expression selecting any instance of two or more back-to-back spaces.

/\s{2}/g是一个正则表达式,选择两个或多个背靠背空间的任何实例。

const myMessage = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis id urna \
    ligula. Suspendisse lobortis ex ut vestibulum venenatis. Donec imperdiet ante odio, \
    nec malesuada diam tristique eget. Lorem ipsum dolor sit amet, consectetur adipiscing \
    elit. Cras in vulputate tellus.`
  .replace(/\s{2,}/g, "");

This outputs a plain, unbroken string.

这将输出一个普通的、完整的字符串。

"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis id urna ligula. Suspendisse lobortis ex ut vestibulum venenatis. Donec imperdiet ante odio, nec malesuada diam tristique eget. Lorem ipsum dolor sit amet, consectetur elit. Cras in vulputate tellus."

“Lorem ipsum dolor sat amet,consectetur adipiscing elit。Duis id urna ligula。Suspendisse lobortis ex ut前庭venenatis。Donec imperdiet ante odio,necmalesuada diam tristique eget。Lorem ipsum dolor 坐 amet,consectetur inc。”