Geu*_*uis 18 javascript ecmascript-6 template-literals
这些天大多数人都在使用es6.一个警告是模板字符串.
我喜欢将我的行字符数限制为80.因此,如果我需要连接一个长字符串,它可以正常工作,因为连接可以是多行,如下所示:
const insert = 'dog';
const str = 'a really long ' + insert + ' can be a great asset for ' +
insert + ' when it is a ' + dog;
Run Code Online (Sandbox Code Playgroud)
但是,使用模板文字尝试这样做只会给你一个多行字符串,其中$ {insert}将狗放在结果字符串中.当您想要将模板文字用于诸如URL汇编等内容时,这并不理想.
我还没有找到一个很好的方法来维护我的行字符限制,仍然使用长模板文字.有人有想法吗?
被标记为被接受的另一个问题只是部分答案.下面是我忘记包含的模板文字的另一个问题.
使用换行符的问题在于,如果不在最终字符串中插入空格,则不允许缩进.即
const insert = 'dog';
const str = `a really long ${insert} can be a great asset for\
${insert} when it is a ${insert}`;
Run Code Online (Sandbox Code Playgroud)
结果字符串如下所示:
a really long dog can be a great asset for dog when it is a dog
Run Code Online (Sandbox Code Playgroud)
总的来说这是一个小问题,但如果有一个允许多行缩进的修复程序会很有趣.
Geu*_*uis 17
这个问题的两个答案,但只有一个可能被认为是最佳的.
在模板文字内部,javascript可以在表达式中使用${}.因此,可以使用缩进的多行模板文字,例如以下内容.需要注意的是表达式中必须存在一些有效的js字符或值,例如空字符串或变量.
const templateLiteral = `abcdefgh${''
}ijklmnopqrst${''
}uvwxyz`;
// "abcdefghijklmnopqrstuvwxyz"
Run Code Online (Sandbox Code Playgroud)
此方法使您的代码看起来像垃圾.不建议.
第二种方法是@SzybkiSasza推荐的,似乎是最好的选择.出于某种原因,尽可能不会出现连接模板文字.我是derp.
const templateLiteral = `abcdefgh` +
`ijklmnopqrst` +
`uvwxyz`;
// "abcdefghijklmnopqrstuvwxyz"
Run Code Online (Sandbox Code Playgroud)
为什么不使用标记模板文字函数?
function noWhiteSpace(strings, ...placeholders) {
let withSpace = strings.reduce((result, string, i) => (result + placeholders[i - 1] + string));
let withoutSpace = withSpace.replace(/$\n^\s*/gm, ' ');
return withoutSpace;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以标记任何你想要换行的模板文字:
let myString = noWhiteSpace`This is a really long string, that needs to wrap over
several lines. With a normal template literal you can't do that, but you can
use a template literal tag to allow line breaks and indents.`;
Run Code Online (Sandbox Code Playgroud)
提供的函数将去除所有换行符和行前制表符和空格,产生以下结果:
> This is a really long string, that needs to wrap over several lines. With a normal template literal you can't do that, but you can use a template literal tag to allow line breaks and indents.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11113 次 |
| 最近记录: |