ES6中模板字符串的天才

ES6是JavaScript的未来,而且已经存在。 这是一个最终的规范,它带来了语言要与当今网络的需求保持竞争所需的许多功能。 ES6中的所有功能都不是适合您的,在本系列文章中,我将展示非常方便且已经可用的功能。

如果查看我编写JavaScript代码,您会发现我总是使用单引号定义字符串而不是双引号。 JavaScript都可以使用-以下两个示例完全相同:

var animal = "cow";

var animal = 'cow';

我之所以喜欢单引号,是因为,首先,它使得以适当的引号属性组合HTML字符串变得更加容易:

// with single quotes, there's no need to 

// escape the quotes around the class value

var but = '<button class="big">Save</button>';



// this is a syntax error:

var but = "<button class="big">Save</button>";



// this works:

var but = "<button class=\"big\">Save</button>";

现在唯一需要转义的时间是在HTML中使用单引号时,这种情况很少见。 我唯一能想到的是内联JavaScript或CSS,这意味着您很可能会对标记做一些可疑或绝望的事情。 即使在您的文本中,最好不要使用单引号,而在印刷方面更令人愉悦。

除了:当然,HTML足够宽容,可以省略引号或在属性周围使用单引号,但是我更喜欢为人类创建可读的标记,而不是依靠解析器的宽恕。 我们之所以宽容HTML5解析器,是因为人们过去曾写过糟糕的标记,而不是以此作为借口。

在document.write的DHTML时代,我已经受够了痛苦,在新弹出窗口和其他可憎的框架集中创建了一个文档,不想再使用转义字符了。 有时,我们需要三元组,这甚至在我们的编辑器中进行颜色编码之前。 一团糟。

用字符串替换表达式?

我更喜欢单引号的另一个原因是,我花了很多时间在非常重要的大型网站上写了很多PHP。 在PHP中,单引号和双引号之间是有区别的。 单引号字符串没有任何替代,而双引号字符串却没有。 这意味着在PHP 3和PHP 4时代,使用单引号的速度要快得多,因为解析器不必遍历字符串来替换值。 这是什么意思的例子:

<?php

  $animal = 'cow';

  $sound = 'moo';

 

  echo 'The animal is $animal and its sound is $sound';

  // => The animal is $animal and its sound is $sound

 

  echo "The animal is $animal and its sound is $sound";

  // => The animal is cow and its sound is moo

?>

JavaScript没有这种替代,这就是为什么我们必须串联字符串才能获得相同的结果。 这非常麻烦,因为您需要始终跳入或跳出引号。

var animal = 'cow';

var sound = 'moo';



alert('The animal is ' + animal + ' and its sound is ' +

 sound);

// => "The animal is cow and its sound is moo"

多行混乱

较长和更复杂的字符串会变得非常混乱,尤其是在我们组装大量HTML时。 最有可能的是,您的整理工具迟早会抱怨在行尾加+后尾随空白。 这基于JavaScript没有多行字符串的问题:

// this doesn't work

var list = '<ul>

  <li>Buy Milk</li>

  <li>Be kind to Pandas</li>

  <li>Forget about Dre</li>

</ul>';

 

// This does, but urgh… 

var list = '<ul>\

  <li>Buy Milk</li>\

  <li>Be kind to Pandas</li>\

  <li>Forget about Dre</li>\

</ul>';

 

// This is the most common way, and urgh, too…

var list = '<ul>' +

'  <li>Buy Milk</li>' +

'  <li>Be kind to Pandas</li>' +

'  <li>Forget about Dre</li>' +

'</ul>';

客户端模板解决方案

为了解决JavaScript中字符串处理和连接混乱的问题,我们做了我们一直做的工作-我们编写了一个库。 HTML模板库很多,其中Mustache.js可能是开创性的。 所有这些都遵循自己的,非标准化的语法,并且在这种思想框架中起作用。 这有点像说您在Markdown中编写内容,然后意识到“ Markdown”的含义有很多不同的想法。

输入模板字符串

随着ES6的出现及其标准化,我们可以为JavaScript感到高兴,因为JavaScript现在在处理字符串方面有了一个新的障碍: Template Strings当前浏览器中对模板字符串支持令人鼓舞:Chrome 44 +,Firefox 38 +, Microsoft Edge和WebKit都已内置。 令人遗憾的是,Safari浏览器还没有,但它将到达那里。

模板字符串的天才之处在于它使用了新的字符串分隔符,既不在HTML中也不在常规文本中使用:反引号( ` )。

现在,使用此代码,我们可以在JavaScript中进行字符串表达式替换:

var animal = 'cow';

var sound = 'moo';

 

alert(`The animal is ${animal} and its sound is ${sound}`);

// => "The animal is cow and its sound is moo"

${}构造可以接受任何返回值JavaScript表达式。 例如,您可以进行计算或访问对象的属性:

var out = `ten times two totally is ${ 10 * 2 }`;

// => "ten times two totally is 20"

 

var animal = {

  name: 'cow',

  ilk: 'bovine',

  front: 'moo',

  back: 'milk',

}

alert(`

  The ${animal.name} is of the 

  ${animal.ilk} ilk, 

  one end is for the ${animal.front}, 

  the other for the ${animal.back}

`);

// => 

/*

  The cow is of the 

  bovine ilk, 

  one end is for the moo, 

  the other for the milk

*/

最后一个示例还向您显示多行字符串不再是问题。

标记模板

使用模板字符串可以做的另一件事是在它们之前添加一个标签,该标签是被调用并以字符串作为参数的函数的名称。 例如,您可以对生成的URL字符串进行编码,而不必始终使用可怕的名为encodeURIComponent的名称。

function urlify (str) {

  return encodeURIComponent(str);

}

 

urlify `http://beedogs.com`;

// => "http%3A%2F%2Fbeedogs.com"

urlify `woah$£$%£^$"`;

// => "woah%24%C2%A3%24%25%C2%A3%5E%24%22"

 

// nesting also works:

 

var str = `foo ${urlify `&&`} bar`;

// => "foo %26%26 bar"

这可行,但依赖于隐式数组到字符串强制。 发送给函数的参数不是字符串,而是字符串和值的数组。 如果使用我在此显示的方式,为了方便起见,它将转换为字符串,但是正确的方法是直接访问数组成员。

从模板字符串中检索字符串和值

在标记函数中,您不仅可以获取完整的字符串,还可以获取其部分。

function tag (strings, values) {

  console.log(strings);

  console.log(values);

  console.log(strings[1]);

}

tag `you ${3+4} it`;

/* =>

 

Array [ "you ", " it" ]

7

it

 

*/

还提供了一组原始字符串,这意味着您将获得字符串中的所有字符,包括控制字符。 例如,假设您使用\n添加换行符。 您将在字符串中获得双精度空格,但在原始字符串中获得\n字符:

function tag (strings, values) {

  console.log(strings);

  console.log(values);

  console.log(strings[1]);

  console.log(string.raw[1]);

}

 

tag `you ${3+4} \nit`;

/* =>

 

Array [ "you ", "  it" ]

7

 

it

 \nit

*/

结论

模板字符串是ES6中可以立即使用的一些小优点之一。 如果必须支持较旧的浏览器,则当然可以将ES6转换为ES5。 您可以使用诸如featuretests.io之类的库或以下代码对模板字符串支持进行功能测试:

var templatestrings = false;

try {

  new Function( "`{2+2}`" );

  templatestrings = true;

} catch (err) {

  templatestrings = false;

} 

 

if (templatestrings) {

    // …

}

以下是有关模板字符串的更多文章:

使用JavaScript进行更多操作

本文是Microsoft技术传播者开发的Web开发系列文章的一部分,内容涉及实用JavaScript学习,开源项目以及互操作性最佳实践,包括Microsoft Edge浏览器和新的EdgeHTML呈现引擎

我们鼓励您使用dev.modern.IE上的免费工具跨浏览器和设备进行测试,包括Microsoft Edge(Windows 10的默认浏览器):

我们的工程师和宣传人员在Microsoft Edge和Web平台上进行了深入的技术学习:

Web平台的更多免费跨平台工具和资源:

翻译自: https://code.tutsplus.com/tutorials/the-genius-of-template-strings-in-es6--cms-24915

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值