Usage of the backtick character (`) in JavaScript

后端 未结 9 2099
囚心锁ツ
囚心锁ツ 2020-11-22 00:51

In JavaScript, a backtick seems to work the same as a single quote. For instance, I can use a backtick to define a string like this:

var s         


        
9条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 01:22

    Backticks (`) are used to define template literals. Template literals are a new feature in ECMAScript 6 to make working with strings easier.

    Features:

    • we can interpolate any kind of expression in the template literals.
    • They can be multi-line.

    Note: we can easily use single quotes (') and double quotes (") inside the backticks (`).

    Example:

    var nameStr = `I'm "Rohit" Jindal`;
    

    To interpolate the variables or expression we can use the ${expression} notation for that.

    var name = 'Rohit Jindal';
    var text = `My name is ${name}`;
    console.log(text); // My name is Rohit Jindal
    

    Multi-line strings means that you no longer have to use \n for new lines anymore.

    Example:

    const name = 'Rohit';
    console.log(`Hello ${name}!
    How are you?`);
    

    Output:

    Hello Rohit!
    How are you?
    

提交回复
热议问题