模板字串

Frontend SELF TW
等級 37 , 課堂 2
開放

3.1 巢狀表達式

在模板字串中可以使用任何表達式,包括函數調用、三元運算符和模板字串中的模板字串。

範例:

在表達式 ${a + b} 中執行數學運算,並將結果插入到字串 result 中。

JavaScript
    
      const a = 5;
      const b = 10;

      const result = `The result of ${a} + ${b} is ${a + b}.`;
      console.log(result); // "The result of 5 + 10 is 15."
    
  

3.2 巢狀模板字串

模板字串可以被巢狀使用,這讓我們能創建複雜的字串。

範例:

呼叫物件 user 的方法 greet() 被巢狀在模板字串 message 中。

JavaScript
    
      const user = {
        name: 'Bob',
        age: 25,
        greet() {
          return `Hello, ${this.name}!`;
        }
      };

      const message = `${user.greet()} You are ${user.age} years old.`;

      console.log(message); // "Hello, Bob! You are 25 years old."
    
  

3.3 標籤模板字串 (Tagged Templates)

標籤模板字串允許調用函數來處理模板字串。這能讓我們對字串進行額外的操作,比如國際化、安全插入 HTML 等等。

語法:

    
      function tag(strings, ...values) {
        // 處理字串和數值
        return 結果;
      }

      const result = tag`模板字串帶 ${變數}`;
    
  

範例:

函數 highlight() 處理字串和數值,並將數值包裹在具有 highlight 類的 HTML 標籤 <span> 中。

JavaScript
    
      function highlight(strings, ...values) {
        return strings.reduce((result, str, i) =>
          `${result}${str}${values[i] || ''}`, '');
      }

      const name = 'Carol';
      const hobby = 'painting';
      const message = highlight`My name is ${name} and I love ${hobby}.`;

      console.log(message);
      // "My name is <span class="highlight">Carol</span> and I love <span class="highlight">painting</span>."
    
  

3.4 安全插入數值

模板字串能幫助我們避免某些常見的安全問題,比如 XSS(跨站指令碼),通過安全地插入數值。這在將用戶數據插入 HTML 時尤其有用。

範例:

函數 safeHTML() 替換數值中的危險字元,防止 XSS 攻擊。

JavaScript
    
      function safeHTML(strings, ...values) {
        return strings.reduce((result, str, i) =>
          `${result}${str}${String(values[i]).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')}`, '');
      }

      const userInput = '<script>alert("XSS")</script>';
      const message = safeHTML`User input: ${userInput}`;

      console.log(message);
      // "User input: &lt;script&gt;alert("XSS")&lt;/script&gt;"
    
  
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION