ES6 template string usage

introduction

ES6 (ECMAScript 2015) introduces many new language features, one of which is template strings. Template strings provide a more convenient and flexible way to handle string concatenation and variable insertion. In this article, we’ll cover the basic syntax and common uses of ES6 template strings.

Chapter 1: Basic Grammar

ES6 template strings use backtick ( )来定义字符串。在模板字符串中,我们可以使用${}` syntax to insert variables or expressions into a string. Here is an example of a basic template string:

const name = 'Alice';
const age = 25;
const message = `My name is ${
      
      name} and I am ${
      
      age} years old.`;
console.log(message);

In the above example, we used ${}the variable sum nameto agebe inserted into the string. When we print messagethe variable, the output will be given My name is Alice and I am 25 years old..

Chapter 2: Multi-line strings

Traditional string concatenation usually requires the use \nof newline characters. In template strings, we can directly use newlines to create multi-line strings to make the code more readable. Here's an example using a multiline string:

const message = `
  Hello,
  Welcome to our website.
  Have a nice day!
`;
console.log(message);

In the above example, when we use backtick ( )将多行字符串括起来,并直接在字符串中使用换行符。当我们打印message` variable, the following will be output:

Hello,
Welcome to our website.
Have a nice day!

Chapter 3: String operations

In addition to inserting variables and creating multi-line strings, template strings also support other string operations, such as string interception, conversion to uppercase or lowercase, etc. Here are some common string manipulation examples:

const str = 'Hello, world!';

console.log(str.startsWith('Hello'));  // true
console.log(str.endsWith('!'));  // true
console.log(str.includes('world'));  // true

console.log(str.toUpperCase());  // HELLO, WORLD!
console.log(str.toLowerCase());  // hello, world!

console.log(str.slice(7));  // world!
console.log(str.substring(7, 12));  // world
console.log(str.substr(7, 5));  // world

In the above example, we used some common string manipulation methods, such as startsWith, endsWithand includesto determine the beginning, end and inclusion relationship of the string. toUpperCaseand toLowerCaseare used to convert strings to uppercase or lowercase. slice, substringand substrare used to intercept part of the string.

in conclusion

ES6's template string provides us with a more convenient and flexible way to handle string concatenation and variable insertion. We can use ${}syntax to insert variables or expressions into strings, create multiline strings, and perform common string operations. I hope this article helps you understand and use ES6 template strings!

The above is the content of the article about how to use ES6 template strings. Hope this helps!

Reference links:

Guess you like

Origin blog.csdn.net/TianXuab/article/details/133197271
Recommended