ES6 JavaScript模板文字-它们可以做什么和不能做什么 [英] ES6 JavaScript template literals - What they can and can't do

查看:55
本文介绍了ES6 JavaScript模板文字-它们可以做什么和不能做什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模板文字使字符串操作容易得多.但是:

Template literals make string manipulation much easier. However:

  1. 与诸如胡子和把手之类的模板库相比,它们能做什么和不能做什么?
  2. 我发现很难找到以下问题的答案:它们可以处理条件吗?他们可以处理循环吗?他们可以处理功能吗?

推荐答案

名称有点模棱两可,但是模板文字不能代替模板引擎.它们的作用仅仅是提供一种更方便的语法来处理字符串.实际上,目标是像CoffeeScript一样将字符串插值引入到核心JavaScript中,以及清除多行字符串的可能性.

The name is a bit ambiguous, but template literals do not replace template engines. They role is only to provide a more convenient syntax to work with strings. In fact, the objective was to bring string interpolation to core JavaScript like CoffeeScript did, plus the possibility of clean multiline strings.

此代码...

let foo = 'Foo',
    bar = 'Bar',
    baz = 'Baz';

console.log(`${foo} ${bar} ${baz}`);

...比这更容易维护:

... is easier to maintain than this one:

var foo = 'Foo',
    bar = 'Bar',
    baz = 'Baz';

console.log(foo + ' ' + bar + ' ' + baz);

此外,此代码...

let str = `Foo
Bar
Baz`;

...比这更易读:

var str = 'Foo\n\
Bar\n\
Baz';

即使模板文字不替换模板引擎,它们也可能对预处理字符串有用(请参阅带标签的模板文字).使用此功能,我们可以例如使用自定义的 htmlentities 函数转义字符串:

Even if they do not replace template engines, template literals may be useful to preprocess strings (see tagged template literals). With this functionality, we can for instance escape strings with a custom htmlentities function:

function htmlentities(raw) {
  let str = raw[0];
    
  return str.replace(/&/g, '&')
            .replace(/>/g, '>')
            .replace(/</g, '&lt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&apos;');
}
    
console.log(htmlentities`&><\"\'`);

在幕后,带标签的模板文字是 sprintf 在许多编程语言中体现的众所周知的字符串操作实践的语法糖:

Under the hood, tagged template literals are syntactic sugar for a well-known string manipulation practice embodied by sprintf in many programming languages:

let foo = 'Foo',
    bar = 'Bar';

function htmlentities(raw, ...args) {
  console.log('String pieces:');
  console.log(raw);
  console.log('String arguments:');
  console.log(args);
  
  return 'Cool, isn\'t it?';
}

console.log(htmlentities`Hello, ${foo} and ${bar}!`);

这篇关于ES6 JavaScript模板文字-它们可以做什么和不能做什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆