1. ``

  • 使用反引号(`` tab键上面的按钮)声明字符串

let str = `定义字符串新的方式`;

  • `${变量名}` -> 拼接变量的方式

let obj = {
    name: 'Kevin',
    age: 41
};
let str = `我叫:${obj.name}, 我的年龄是:${obj.age}`;

  • 可以在 `` 里面直接进行换行

let str = `我叫:Kevin,

我的年龄是:18`;

  • 使用 '' 和 使用 `` 定义字符串的对比

let obj = {
    name: 'Kevin',
    age: 41
};

let str1 = '我叫:' + obj.name + ', 我的年龄是:' + obj.age;
let str2 = `我叫:${obj.name}, 我的年龄是:${obj.age}`;

2. 字符串查找

  • .includes(str) -> 判断某个字符是否在str里面

    • 返回值: true 或 false

let str = 'Kevin';

console.log(str.includes('ev'));  // true
console.log(str.includes('ab'));  // false

  • .startsWith('str', num) -> 判断是否以什么开头

    • 返回值: true 或 false
    • 如果有第二参数: 从下标为1的字符开始进行判断下标1的字符是否以e开头 (下标从 0 开始数起)

let str = 'Kevin';

console.log(str.startsWith('Ke'));  // true
console.log(str.startsWith('Ae'));  // false
console.log(str.startsWith('e', 1));  // true
console.log(str.startsWith('e', 0));  // false

  • .endsWith('str', num) -> 判断是否以什么结尾

    • 返回值: true 或 false
    • 如果有第二参数: 从下标为1的字符开始进行判断下标1的字符是否以e结尾 (下标从 1 开始数起)

let str = 'Kevin';

console.log(str.endsWith('n'));  // true
console.log(str.endsWith('e'));  // false
console.log(str.endsWith('n', str.length));  // true
console.log(str.endsWith('n', str.length - 1));  // false

  • .repeat(num) -> 复制几遍

let str = 'Kevin';

console.log(str.repeat(5));  // KevinKevinKevinKevinKevin