防止ES6模板字符串中出现换行 [英] Prevent line breaks in ES6 template string

查看:264
本文介绍了防止ES6模板字符串中出现换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ESLint:第403行的最大行长度超过了120(最大镜头)

ESLint: Line 403 exceeds the maximum line length of 120 (max-len)

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

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

var string = `Let me be the 'throws Exception’ to your 'public static void 
              main (String[] args)’. I will accept whatever you give me my ${love}.`
console.log(string);

结果:

 Let me be the 'throws Exception’ to your 'public static void 
 main (String[] args)’. I will accept whatever you give me xxx.

我的期望:

Let me be the 'throws Exception’ to your 'public static void main (String[] args)’. I will accept whatever you give me xxx.

要求:

  1. 我无法禁用eslint规则,因为必须执行.

  1. I cannot disable the eslint rule, as enforcement is necessary.

由于数据是动态的,因此无法将数据放在单独的文件中.

I cannot put the data in a separate file, as the data is dynamic.

我无法连接多个较短的字符串,因为这很繁琐.

I cannot concatenate multiple shorter strings, since that is too much work.

推荐答案

这是预期的行为.模板文字可以解决的重要问题之一是多行字符串:

This is expected behaviour. One of the important problems that template literals solve is multiline strings:

在源代码中插入的任何换行符都是模板文字的一部分.

Any new line characters inserted in the source are part of the template literal.

如果需要进一步处理字符串,则可以使用其他JS功能(例如正则表达式)来完成:

If the string needs to be processed further, this can be done with other JS features, like regular expressions:

var string = `Let me be the 'throws Exception’ to your 'public static void 
              main (String[] args)’. I will accept whatever you give me.`
              .replace(/[\n\r]+ */g, ' ');

String.raw 是用于转换模板文字的内置函数.可以使用标记功能为模板文字提供自定义行为.应当注意,String.raw在处理特殊字符.如果在字符串中使用它们,则应另外使用

String.raw is built-in function to transform template literals. It's possible to use tag function to provide custom behaviour to template literals. It should be noticed that String.raw differs from default template transformer in terms of how it processes special characters. If they are used in a string, they should be additionally processed with unescape-js or similar helper function.

function singleLine(strsObj, ...values) {
  const strs = strsObj.raw
  .map(str => str.replace(/[\n\r]+ */g, ' '))
  .map(unescapeSpecialChars);
  return String.raw(
    {raw: strs },
    ...values
  );
}


var string = singleLine`Let me be the 'throws Exception’ to your 'public static void 
              main (String[] args)’. I will accept whatever you give me.`;

这篇关于防止ES6模板字符串中出现换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆