方法

includes()

:::info 判断字符串中是否存在某个字符,返回布尔值 :::

  1. const str = "abcdefg";
  2. console.log(str.includes("a")); // true

startsWith() / endsWith()

:::info 判断字符串是否是以某个值开头/结尾,返回布尔值 :::

  1. const str = "abcdefg";
  2. console.log(str.startsWith("abc")); // true
  3. console.log(str.endsWith("fg")); // true

repeat()

:::info 将字符串重复多少次,返回更改后的字符串 :::

  1. const str = "abcdefg";
  2. console.log(str.repeat(3)); // abcdefgabcdefgabcdefg
  3. console.log(str); // abcdefg

特殊值:

  1. console.log("abc".repeat(2.3)); // abcabc 转换为整数2
  2. console.log("abc".repeat(NaN)); // abc 不进行操作

padStart() / padEnd()

:::info 在字符串前面/后面把某字符串填充多少次,返回新字符串
参数1:当前字符串需要填充到的目标长度。如果这个数值小于当前字符串的长度,则返回当前字符串本身
参数2:填充字符串 :::

  1. const str = "abcdefg";
  2. console.log(str.padStart(10, "***")); // ***abcdefg 从g往前数
  3. console.log(str); // abcdefg
  1. const str = "abcdefg";
  2. console.log(str.padEnd(10, "*")); // abcdefg*** 从a往后数
  3. console.log(str); // abcdefg

模版字符串

ES5的时候如果字符串想要拼接多个变量需要频繁的使用+

  1. let name = "web";
  2. let info = "developer";
  3. let str = "I am a " + name + " " + info;
  4. console.log(str); // I am a web developer

这样的写法非常的不方便,ES6新增了模版字符串,用```包裹,${}`表示变量:

  1. let name = "web";
  2. let info = "developer";
  3. let str = `I am a ${name} ${info}`;
  4. console.log(str); // I am a web developer

模版字符串内还可以是表达式:

  1. let x = 1;
  2. let y = 2;
  3. let z = `${x} + ${y} = ${x + y}`;
  4. console.log(z); // 1 + 2 = 3

模版字符串内还可以是函数:

  1. function fn() {
  2. return "Hello Word";
  3. }
  4. console.log(`foo ${fn()} bar`); // foo Hello Word bar

模版字符串嵌套字符串:

  1. let msg = `Hello ${'palce'}`;
  2. console.log(msg); // Hello palce

例如我想实现一个html的数据模版:

  1. const temp = (arr) => `
  2. <table>
  3. ${arr
  4. .map((el) =>`
  5. <tr>
  6. <td>${el.firstName}</td>
  7. <td>${el.lastName}</td>
  8. </tr>
  9. `).join("")
  10. }
  11. </table>`;
  12. const data = [
  13. {
  14. firstName: "zhang",
  15. lastName: "san",
  16. },
  17. {
  18. firstName: "li",
  19. lastName: "si",
  20. },
  21. ];
  22. console.log(temp(data));

标签模版

在模版字符串的前面紧挨一个函数名表示模版字符串的标签模版,标签模版是函数调用的一种特殊形式。「标签」指的就是函数,紧跟在后面的模板字符串就是它的参数。
但是,如果模板字符里面有变量,就不是简单的调用了,而是会将模板字符串先处理成多个参数,再调用函数。

  1. let a = 5;
  2. let b = 10;
  3. testFun`Hello ${a + b} world ${a * b}`;
  4. // 等同于 testFun(['Hello ', ' world ', ''], 15, 50);
  5. function testFun($, $1, $2) {
  6. console.log($); // ['Hello ', ' world ', '']
  7. console.log($1); // 15
  8. console.log($2); // 50
  9. }

:::info 参数1是模板字符串中那些没有变量替换的部分,也就是说,变量替换只发生在数组的第一个成员与第二个成员之间、第二个成员与第三个成员之间,以此类推。 :::

所以我们可以在标签模版函数中做一些处理后返回数据:

  1. let a = 5;
  2. let b = 10;
  3. let str = testFun`Hello ${a + b} world ${a * b}`;
  4. function testFun($, $1, $2) {
  5. return "这是一个测试案例";
  6. }
  7. console.log(str); // "这是一个测试案例"