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

CSS screen size adaptive implementation example

To achieve CSS screen size adaptation, we must fi...

How to quickly use mysqlreplicate to build MySQL master-slave

Introduction The mysql-utilities toolset is a col...

Parameters to make iframe transparent

<iframe src="./ads_top_tian.html" all...

HTML+jQuery to implement a simple login page

Table of contents Introduction Public code (backe...

JavaScript setTimeout and setTimeinterval use cases explained

Both methods can be used to execute a piece of ja...

Detailed explanation of the binlog log analysis tool for monitoring MySQL: Canal

Canal is an open source project under Alibaba, de...

MySQL 5.5 installation and configuration graphic tutorial

Organize the MySQL 5.5 installation and configura...

Notes on configuring multiple proxies using vue projects

In the development process of Vue project, for th...

Detailed analysis of the syntax of Mysql update to modify multiple fields and

When updating a record in MySQL, the syntax is co...

Multiple ways to calculate age by birthday in MySQL

I didn't use MySQL very often before, and I w...

MySQL database master-slave replication and read-write separation

Table of contents 1. Master-slave replication Mas...

Detailed explanation of the use of title tags and paragraph tags in XHTML

XHTML Headings Overview When we write Word docume...

3 codes for automatic refresh of web pages

In fact, it is very simple to achieve this effect,...