Lok*_*wal 3 javascript ecmascript-6 template-strings
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);
Run Code Online (Sandbox Code Playgroud)
结果:
Let me be the 'throws Exception’ to your 'public static void
main (String[] args)’. I will accept whatever you give me xxx.
Run Code Online (Sandbox Code Playgroud)
我的期望:
Let me be the 'throws Exception’ to your 'public static void main (String[] args)’. I will accept whatever you give me xxx.
Run Code Online (Sandbox Code Playgroud)
要求:
我不能禁用 eslint 规则,因为强制执行是必要的。
我不能将数据放在单独的文件中,因为数据是动态的。
我无法连接多个较短的字符串,因为这工作量太大。
这是预期的行为。模板文字解决的重要问题之一是多行字符串:
插入到源中的任何换行符都是模板文字的一部分。
如果需要进一步处理字符串,可以使用其他 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, ' ');
Run Code Online (Sandbox Code Playgroud)
String.raw是用于转换模板文字的内置函数。可以使用标签函数为模板文字提供自定义行为。应该注意的是,它String.raw与默认模板转换器的不同之处在于它如何处理特殊字符。如果它们在字符串中使用,则应使用unescape-js或类似的辅助函数对其进行额外处理。
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.`;
Run Code Online (Sandbox Code Playgroud)