Difference between Template literals and Tagged template literals?

前端 未结 2 1748
野趣味
野趣味 2020-11-28 14:55

ES6 has two new kinds of literals:

  • template literals
  • tagged template literals.

Template literals: multi-line string l

相关标签:
2条回答
  • 2020-11-28 15:27

    ES6 has new features

    Template literals

    and

    Tagged template literals (Tagged templates)

    which make working with strings easier. You wrap your text in `backticks`

    With this we can:

    1.Interpolate variables

    let foo = "abc";
    
    console.log(`Welcome ${foo}`);  // Welcome abc
    

    2.Interpolate any kind of expression

    console.log(`2+3 = ${2+3}`) // 2+3 = 5
    

    3.Declare strings with both ' and " quotation marks without having to escape anything.

    let foo = `foo is 'bar', "bar" is foo`
    
    console.log(foo); // "foo is 'bar', "bar" is foo"
    

    4.Cleaner syntax for multi-line string

    let text = `foo is bar
    
    bar is foo`  
    
    console.log(text);
    
    //"foo is bar
    
    //bar is foo"
    

    5.Tagged templates, we can pass template literals to a function, here is how:

    let person = 'Mike';
    let age = 28;
    
    let output = myTag `that ${ person } is ${ age }`;
    
    function myTag(strings, personExp, ageExp) {
    
    //strings[0] gets value "that "
    //strings[1] gets value " is "
    //personExp  gets value " Mike "
    //ageStr     gets value "28"
    
    return strings[0] + personExp + strings[1] + ageExp;
    }
    
    console.log(output);
    
    // that Mike is 28
    

    6.String.raw, we can get the raw form, here is the example:

    let text = String.raw `The "\n" newline won't result in a new line.'
    console.log(text);
    // The "\n" newline won't result in a new line.
    

    Hope this helps!!!!!!

    0 讨论(0)
  • 2020-11-28 15:31

    With tagged template literal we able to modify the output of template literals using a function. The first argument contains an array of string literals. The second, and each argument after the first one, are the values of the processed substitution expressions. We can use any name to our function.

    var a = 1;
    var b = 2;
    
    function tag(strings, ...values) {
     console.log(strings[0]); // "One "
     console.log(strings[1]); // " Two"
     console.log(strings[2]); // " Three"
     console.log(values[0]); // 1
     console.log(values[1]); // 2
    }
    
    tag`One ${ a } Two ${ b } Three`;
    
    // One 
    // Two 
    // Three
    // 1
    // 2
    

    here our our tag function will return the output with custom formats

    0 讨论(0)
提交回复
热议问题