89-字符串常用方法

  • 在js中字符串可以看做一个特殊的数组, 所以大部分数组的属性/方法字符串都可以使用

  • 1. 获取字符串长度 .length
        let str = "abcd";
        console.log(str.length);  // 4
    
  • 2. 获取某个字符 [索引] / charAt
          let str = "abcd";
    
          let ch = str[1]; // 高级浏览器才支持, 有兼容性问题, 不推荐使用
          console.log(ch);  // b
    
          let ch = str.charAt(1); // 没有兼容性问题
          console.log(ch);  // b
    
  • 3. 字符串查找 indexOf / lastIndexOf / includes
          let str = "vavcd";
    
          let index = str.indexOf("v");    // 0
          let index = str.lastIndexOf("v");   // 2
          console.log(index);
    
          let result = str.includes("c"); // true
          let result = str.includes("p"); // false
          console.log(result);
    
  • 4. 拼接字符串 concat / +
        let str1 = "www";
        let str2 = "it666";
    
        let str = str1 + str2;   // 推荐
        console.log(str);  // wwwit666
    
        let str = str1.concat(str2);
        console.log(str);  // wwwit666
    
  • 5. 截取子串
        let str = "abcdef";
    
        let subStr = str.slice(1, 3);    // bc
        let subStr = str.substring(1, 3);   // bc   推荐
        let subStr = str.substr(1, 3);   // bcd  从索引为1的位置开始截取3个
        console.log(subStr);
    
  • 6.字符串切割
        // 数组转为字符串
        let arr = [1, 3, 5];
        let str = arr.join("-");
        console.log(str);  // 1-3-5
    
        // 字符串转为数组
        let str = "1-3-5";
        let arr = str.split("-");
        console.log(arr);  // 135
    
  • 7. 判断是否以指定字符串开头( startsWith) ES6
        let str = "www.it666.com";
    
        let result = str.startsWith("www");
        console.log(result);    // true
    
  • 8. 判断是否以指定字符串结尾 (endsWith) ES6
        let str = "lnj.png";
    
        let result = str.endsWith("png");
        console.log(result);    // true
    
  • 9. 字符串模板 ( `` ) ES6
        let str = "
      \n" + "
    • 我是第1个li
    • \n" + "
    • 我是第2个li
    • \n" + "
    • 我是第3个li
    • \n" + "
    "; let str = `
    • 我是第1个li
    • 我是第2个li
    • 我是第3个li
    `;
        let name = "lnj";
        let age = 34;
    
        // let str = "我的名字是" + name + ",我的年龄是" + age;
    
        let str = `我的名字是${name}, 我的年龄是${age}`;
        console.log(str);  // 我的名字是lnj, 我的年龄是34
    

你可能感兴趣的:(89-字符串常用方法)