模板字符串功能

  1. //ES6  字符串插值
    var customer = { name: "Foo" }
    var card = { amount: 7, product: "Bar", unitprice: 42 }
    var message = `Hello ${customer.name},
    want to buy ${card.amount} ${card.product} for
    a total of ${card.amount * card.unitprice} bucks?`
    
    //ES5
    var customer = { name: "Foo" };
    var card = { amount: 7, product: "Bar", unitprice: 42 };
    var message = "Hello " + customer.name + ",\n" +
    "want to buy " + card.amount + " " + card.product + " for\n" +
    "a total of " + (card.amount * card.unitprice) + " bucks?";
    

      链接:http://es6-features.org/#StringInterpolation

  2. //ES6    自定义插值 
    get`http://example.com/foo?bar=${bar + baz}&quux=${quux}`
    
    //ES5 
    get([ "http://example.com/foo?bar=", "&quux=", "" ],bar + baz, quux);
    

      

  3. //ES6    原始字符串访问     访问原始模板字符串内容(反斜杠不被解释)。 
    function quux (strings, ...values) {
        strings[0] === "foo\n"
        strings[1] === "bar"
        strings.raw[0] === "foo\\n"
        strings.raw[1] === "bar"
        values[0] === 42
    }
    quux`foo\n${ 42 }bar`
    
    String.raw`foo\n${ 42 }bar` === "foo\\n42bar"
    
    //ES5
    ES5中没有等值 
    

    语法:

  4. 语法:
    String.raw`templateStr`;
    String.raw(obj, ...substitutions);
    
    参数:
    
    templateStr
    必需。模板字符串。
    obj
    必需。一个使用对象文本表示法指定的格式正确的对象,例如 { raw: “value” }。
    ...substitutions
    可选。一个数组(rest 参数),包含一个或多个替换值。
    

      

    function log(arg) {
        if(console && console.log) {
            console.log(arg);
        }
    };
    
    var name = "bob";
    
    log(`hello \t${name}`);
    log(String.raw`hello \t${name}`);
    // The following usage for String.raw is supported but
    // is not typical.
    log(String.raw({ raw: 'fred'}, 'F', 'R', 'E'));
    
    // Output:
    // hello   bob
    // hello \tbob
    // fFrReEd              ???????
    


    String.raw 函数旨在与模板字符串一起使用。原始字符串将包含存在于字符串中的任何转义字符和反斜杠。

  5. 链接:http://es6-features.org/#RawStringAccess

猜你喜欢

转载自www.cnblogs.com/Longhua-0/p/9191839.html