Tagged template literals in Javascript

栏目: IT技术 · 发布时间: 3年前

内容简介:In ES6 the templated literals were added in Javascript. They are used to interpolate values in a string.So, this made things a bit more elegant when concatenating strings.But we can do more than this. We can define tagged template literals. Basically, they

In ES6 the templated literals were added in Javascript. They are used to interpolate values in a string.

const name = 'Tom'
const age = 20;
const myString = `The name is ${name} and the age is ${age}.`;
/* 
myString is now "The name is Tom and the age is 20."
before  ES6 the templated literals we had to write:
myString = "The name is " + name + " and the age is " + age "."
*/

So, this made things a bit more elegant when concatenating strings.

But we can do more than this. We can define tagged template literals. Basically, they are a combination of a tag function and a string template literal . What's returned from the tag function will determine the final format of the string.

Let's say we want to show a string like this one in the below picture.

Tagged template literals in Javascript

The basic string literal will just alow use to write this:

const text = `${p.name} is ${p.age} years old.`;

However, with the tagged template literals we can say:

const text = setHighlightTags `${p.name} is ${p.age} years old.`;

We can name the tag function however we want. In our example the setHighlightTags is defined as:

function setHighlightTags(strings, ...values) {
   let str = '';
   strings.forEach((string, i) => {
       str += string;
       if(values[i]) 
          str += `<span class='hl'>${values[i]} </span>`;
   });
   return str;
}

And the .hl CSS class has just some simple rules:

.hl {
    background-color: yellow;
    padding: 2px 10px;
}

And that's pretty much all we need. We can get more creative when we need it. There are libraries, like styled-components (React) or chalk (for colorful logs) that take this feature to the next level.

If you want you can read more about it here . Also, check out below the full codepen for this example:

See the Pen
by JS Craft ( @js-craft )

on CodePen .

I hope you have enjoyed this article and if you would like to get more articles about React and frontend development you can always sign up for my email list.


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

鳥哥的Linux私房菜(第四版)

鳥哥的Linux私房菜(第四版)

鳥哥 / 碁峰資訊股份有限公司 / 2016-1-25 / TWD 980.00

本書前三版均蟬聯電腦專業書籍Linux暢銷排行榜Top1,為地表最暢銷的Linux中文書籍! 您是有意學習Linux的小菜鳥,卻不知如何下手?您是遨遊Linux的老鳥,想要一本資料豐富的工具書?本書絕對是最佳選擇! ※鳥哥傾囊相授,內容由淺入深 書中包含了鳥哥從完全不懂Linux到現在的所有歷程,鳥哥將這幾年來的所知所學傾囊相授,以最淺顯易懂的文字帶領您進入Linux的世界。 ......一起来看看 《鳥哥的Linux私房菜(第四版)》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器