相关疑难解决方法(0)

ES6模板文字比字符串连接更快吗?

有人做过基准吗?我很好奇,如果使用字符串连接或使用Node和现代浏览器中的模板文字,HTML生成代码更快.

例如:

字符串连接

"<body>"+
  "<article>"+
    "<time datetime='" + date.toISOString() +"'>"+ date +"</time>"+
  "</article>"+
"</body>"
Run Code Online (Sandbox Code Playgroud)

模板文字

`<body>
  <article>
    <time datetime='${ date.toISOString() }'>${ date }</time>
  </article>
</body>`
Run Code Online (Sandbox Code Playgroud)

javascript string performance templates ecmascript-6

64
推荐指数
2
解决办法
2万
查看次数

模板字符串ES6可防止换行

我有一个长字符串,我使用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);
Run Code Online (Sandbox Code Playgroud)

结果:

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:
Run Code Online (Sandbox Code Playgroud)

我的期望:

As all string substitutions in …
Run Code Online (Sandbox Code Playgroud)

javascript ecmascript-6 template-strings

50
推荐指数
5
解决办法
2万
查看次数

es6多行模板字符串,没有新行,允许缩进

这些天大多数人都在使用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)

javascript ecmascript-6 template-literals

18
推荐指数
2
解决办法
1万
查看次数

如何删除模板文字中的多余空格?

当我创建模板文字时,我会使用trim() 来删除多余的空间。但我注意到,当我在 JS 函数中执行此操作时,它仍然会创建额外的制表符或空白。

  function BottlesOfBeer()  {
    
        for (i = 99; i>=1; i--) {
    
            if (i === 1) {        
                var oneBottle = "1 bottle of beer on the wall, 1 bottle of beer.\n" +
                                "Take one down and pass it around, no more bottles of beer on the wall.\n" +
                                "No more bottles of beer on the wall, no more bottles of beer.\n" +
                                "Go to the store and buy some more, 99 bottles of beer on the wall.";        
                
                console.log(oneBottle); …
Run Code Online (Sandbox Code Playgroud)

javascript string function

6
推荐指数
1
解决办法
5972
查看次数