ESLint:第 403 行超过最大行长度 120 (max-len)
我有一个很长的字符串,是使用 ES6 模板字符串构建的,但我希望它没有换行符:
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);
Result:
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.
要求:
我无法禁用 eslint 规则,因为强制执行是必要的。
我无法将数据放在单独的文件中,因为数据是动态的。
我无法连接多个较短的字符串,因为这工作量太大。
这是预期的行为。模板文字解决的重要问题之一是多行字符串 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Multi-line_strings:
源中插入的任何换行符都是模板文字的一部分。
如果需要进一步处理字符串,可以使用其他 JS 功能来完成,例如正则表达式:
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 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw是用于转换模板文字的内置函数。可以使用标签函数为模板文字提供自定义行为。需要注意的是String.raw
与默认模板转换器的不同之处在于它的处理方式特殊字符 https://learn.microsoft.com/en-us/scripting/javascript/advanced/special-characters-javascript#escape-sequences。如果它们在字符串中使用,则应另外处理unescape-js https://github.com/iamakulov/unescape-js/blob/master/src/index.js#L35-L49或类似的辅助函数。
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.`;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)