JS ES new features template string

JS ES new features template string

1. What is a template string?

Template Template String is an enhanced version of string, which uses backticks (```) to replace double quotes and single quotes in Spectrum string. It can be used as a normal string, or it can be used to define multi-line strings or embed variables in strings.

Common usage is as follows:

// A string wrapped with the ` symbol is called a template string let str = `this is str`
console.log(typeof str, str); //string this is str

2. Multi-line template strings

The difference between the template strings provided by ECMAScript 2015 and ordinary strings is that the spaces, indentations, and line breaks in the template strings are all preserved.

The sample code is as follows:

let str = `this 
      is str`
console.log(typeof str, str);
/*
  string this 
      is str
*/


2.1 Template Strings with Expressions

Template strings support embedded expressions. The syntax structure is as follows:

`${expression}`


The sample code is as follows:

let str1 = `this is str1`
let str2 = `this is str2`
// Just write the expression into ${} let and = `${str1} and ${str2}`
console.log(and); // this is str1 and this is str2


3. Tagged Template Strings

The functions of template strings are not limited to the above. It may be followed by the name of a function that will be called to process the template string. This is called a tagged tagged template function.

let str = 'str'
console.log `this is ${str}`;
// Equivalent to console.log(['this is ', ''], str);


Tag templates are not actually templates, but a special form of function calls. The "label" refers to the function, and the template string that follows it is its parameters.

4. Raw Strings

In the first argument of the tag function, there is a special attribute raw that can be used to access the original string of the template string, without the special characters replaced.

The sample code is as follows:

/*
  Raw strings are used in tagged template strings. There is a raw attribute in the first parameter of the function, which can get the raw string of the string.
  * The so-called original string refers to the content when the template string is defined, not the content after processing*/
function tag(string) {
  console.log(string.raw[0]);
}
tag `string test line1 \n string test line2` // string test line1 \n string test line2


In addition, using String.raw() method to generate a raw string is the same as creating it with the default template function and string concatenation.

The sample code is as follows:

let str = String.raw `Hi\n${2+3}!`;
// , the character after Hi is not a newline character, \ and n are two different characters console.log(str); // Hi\n5!


5. Determine whether a string is contained

5.1 includes() method

The includes() method is used to determine whether a string is contained in another string, and returns true or false based on the determination result.

The syntax structure is as follows:

str.includes(searchString[, position])


Parameter Description:

  • searchString : The string to search for within this string.
  • position : (optional) The index position in the current string from which to start searching for the substring. The default value is 0.

It is worth noting that the includes() method is case sensitive.

The sample code is as follows:

let str = 'abcdef';
console.log(str.includes('c')); // true
console.log(str.includes('d')); // true
console.log(str.includes('z')); // false
console.log(str.includes('A')); // false


The includes() method provided by ECMAScript 2015 is case-sensitive. Now we extend it to be case-insensitive.

The sample code is as follows:

String.prototype.MyIncludes = function (searchStr, index = 0) {
  // Change all the strings to be judged to lowercase let str = this.toLowerCase()
  // Change the passed string to lowercase searchStr = searchStr.toLowerCase();
  return str.includes(searchStr, index)
}
let str = 'abcdef';
console.log(str.MyIncludes('c')); // true
console.log(str.MyIncludes('d')); // true
console.log(str.MyIncludes('z')); // false
console.log(str.MyIncludes('A')); // true


5.2startsWith() method

The startsWith() method is used to determine whether the current string starts with another given substring and return true or false based on the judgment result.

The syntax structure is as follows:

str.startsWith(searchString[, position])


Parameter Description:

  • searchString : The string to search for within this string.
  • position : (optional) The index position in the current string from which to start searching for the substring. The default value is 0.

It is worth noting that the startsWith() method is case sensitive.

The sample code is as follows:

let str = 'abcdef';

/*
  * The startsWith() method is used to determine whether the current string starts with another given substring, and returns true or false based on the determination result.
  * str.startsWith(searchString[, position])
    Parameter Description searchString: The string to be searched in this string. 
      position: (optional) The index position in the current string from which to start searching for the substring. The default value is 0.
  !It is worth noting that the startsWith() method is case sensitive.
*/
console.log(str.startsWith('a')); // true
console.log(str.startsWith('c', 2)); // true
console.log(str.startsWith('c')); // flase


5.3 endsWith() method

The endsWith() method is used to determine whether the current string "ends" with another given substring, and returns true or false based on the judgment result.

The syntax structure is as follows:

str.endsWith(searchString[, position])


Parameter Description:

  • searchString : The string to search for within this string.
  • position : (optional) The index position in the current string from which to start searching for the substring. The default value is 0.

It is worth noting that the endsWith() method is case sensitive.

The sample code is as follows:

let str = 'abcdef';

console.log(str.endsWith('f')); // true
console.log(str.endsWith('c', 3)); // true
console.log(str.endsWith('c')); // flase


The following two methods can extend a case-insensitive one by themselves.

This is the end of this article about the new feature of JS ES template string. For more relevant ES template string content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of template strings in JavaScript ES6

<<:  Example code for CSS pseudo-classes to modify input selection style

>>:  A brief analysis of whether using iframe to call a page will cache the page

Recommend

Detailed explanation of Docker working mode and principle

As shown in the following figure: When we use vir...

Implementation of sharing data between Docker Volume containers

What is volume? Volume means capacity in English,...

Let’s take a look at JavaScript precompilation (summary)

JS running trilogy js running code is divided int...

An audio-visual Linux distribution that appeals to audiophiles

I recently stumbled upon the Audiovisual Linux Pr...

How to install and configure Docker nginx

Download Nginx image in Docker docker pull nginx ...

Docker uses nextcloud to build a private Baidu cloud disk

Suddenly, I needed to build a private service for...

A brief introduction to MySQL database optimization techniques

A mature database architecture is not designed wi...

Detailed explanation of this pointing problem in JavaScript

Preface Believe me, as long as you remember the 7...

Detailed tutorial on how to quickly install Zookeeper in Docker

Docker Quickly Install Zookeeper I haven't us...

Docker installs Redis and introduces the visual client for operation

1 Introduction Redis is a high-performance NoSQL ...

Explanation of Truncate Table usage

TRUNCATE TABLE Deletes all rows in a table withou...

Teach you how to implement the observer mode in Javascript

Table of contents What is the Observer Pattern? S...

MySQL Flush-List and dirty page flushing mechanism

1. Review The Buffer Pool will be initialized aft...

Introduction to JavaScript built-in objects

Table of contents 1. Built-in objects 2. Math Obj...

MySql 8.0.11 installation and configuration tutorial

Official website address: https://dev.mysql.com/d...