Home  >  Article  >  Web Front-end  >  What is javascript template string

What is javascript template string

青灯夜游
青灯夜游Original
2022-02-08 15:38:332461browse

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