search
HomeWeb Front-endFront-end Q&AWhat is javascript template string
What is javascript template stringFeb 08, 2022 pm 03:38 PM
javascript

Template string is a new string literal introduced in ES6 that allows embedded expressions. It is an enhanced version of string. It uses backticks to replace the double characters in ordinary strings. Quotes and single quotes. By using template literals, you can use both single and double quotes in a string.

What is javascript template string

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Template literal is a string literal that allows embedded expressions. It is a new string literal introduced in ES6. You can use multiline strings and string interpolation functions. They were called "template strings" in previous versions of the ES2015 specification.

Template strings use backticks (` `) instead of double quotes and single quotes in ordinary strings. Template strings can contain placeholders for specific syntax (${expression}). The expression in the placeholder and the surrounding text are passed together to a default function, which is responsible for concatenating all the parts. If a template string starts with an expression, the string is called a tagged template String, this expression is usually a function, which will be called after the template string is processed. You can use this function to operate on the template string before outputting the final result. When using backtick (`) within a template string, you need to add an escape character (\) in front of it.

`\`` === "`" // --> true

Template strings can be used as ordinary strings, can also be used to define multi-line strings, or embed variables in strings.

Common usage is as follows:

// 使用 ` 符号包裹的字符串称为模板字符串
let str = `this is str`
console.log(typeof str, str); //string this is str

Multi-line template string

The template string provided by ECMAScript 2015 is different from the ordinary string. The spaces, indents, and newlines in the template string will be preserved.

The sample code is as follows:

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

1. Template string with expressions

The template string supports embedded expressions, and the syntax structure is as follows:

`${expression}`

The sample code is as follows:

let str1 = `this is str1`
let str2 = `this is str2`
// 只需要将表达式写入 ${} 中
let and = `${str1} and ${str2}`
console.log(and); // this is str1 and this is str2

Tagged template string

The functions of template string are not just the above. It can follow the name of a function that will be called to process this template string. This is called the tagged template feature.

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

Tag template is not actually a template, but a special form of function call. "Label" refers to the function, and the template string immediately following it is its parameter.

Original string

In the first parameter of the tag function, there is a special attribute raw, through which you can access the original string of the template string , rather than specially replaced characters.

The sample code is as follows:

/*
  原始字符串 应用在带标签的模板字符串中
  * 在函数的第一个参数中存在 raw 属性,该属性可以获取字符串的原始字符串。
  * 所谓的原始字符串,指的是模板字符串被定义时的内容,而不是处理之后的内容
*/
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 the String.raw() method to get the original string of the function key is the same as the default template function and string connection creation.

The sample code is as follows:

let str = String.raw `Hi\n${2+3}!`;
// ,Hi 后面的字符不是换行符,\ 和 n 是两个不同的字符
console.log(str); // Hi\n5!

Judge whether a string is included

1, includes() method

includes The () 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 be searched in this string.

  • position: (Optional) The index position of the current string 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 a case-insensitive one ourselves,

The sample code is as follows:

String.prototype.MyIncludes = function (searchStr, index = 0) {
  // 将需要判断的字符串全部改成小写形式
  let str = this.toLowerCase()
  // 将传入的字符串改成小写形式
  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

2. startsWith() method

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

The syntax structure is as follows:

str.startsWith(searchString[, position])

Parameter description:

  • searchString: The string to be searched in this string.

  • position: (Optional) The index position of the current string 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';
/*
  * startsWith() 方法用来判断当前字符串是否以另外一个给定的子字符串开头, 并根据判断结果返回 true 或 false。
  * str.startsWith(searchString[, position])
    参数说明
      searchString: 要在此字符串中搜索的字符串。 
      position: (可选) 从当前字符串的哪个索引位置开始搜寻子字符串, 默认值为 0。
  !值得注意的是startsWith() 方法是区分大小写的。
*/
console.log(str.startsWith('a')); // true
console.log(str.startsWith('c', 2)); // true
console.log(str.startsWith('c')); // flase

3. endsWith() method

endsWith() method is used to determine whether the current string is based on another given substring. The "end" of the string returns true or false according to the judgment result.

The syntax structure is as follows:

str.endsWith(searchString[, position])

Parameter description:

  • searchString: The string to be searched in this string.

  • position: (Optional) The index position of the current string 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 be used to expand a case-insensitive one.

【Related recommendations: javascript learning tutorial

The above is the detailed content of What is javascript template string. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),