让chartGPT 带我们复习js基础知识 字符串截取(1)

70 阅读2分钟

JavaScript 中常用的字符串截取方法的列表,并按照 Markdown 格式生成:

  1. substring(startIndex, endIndex)

    • 用途:返回指定索引范围内的子串。
    • 示例:
      const str = "Hello, World!";
      const sub = str.substring(7, 12);
      console.log(sub);  // 输出 "World"
      
  2. substr(startIndex, length)

    • 用途:返回从指定索引开始指定长度的子串。
    • 示例:
      const str = "Hello, World!";
      const sub = str.substr(7, 5);
      console.log(sub);  // 输出 "World"
      
  3. slice(startIndex, endIndex)

    • 用途:返回从指定索引开始到指定索引前的子串。
    • 示例:
      const str = "Hello, World!";
      const sub = str.slice(7, 12);
      console.log(sub);  // 输出 "World"
      
  4. split(separator, limit)

    • 用途:将字符串拆分为数组,根据指定的分隔符进行分割。
    • 示例:
      const str = "Hello, World!";
      const arr = str.split(", ");
      console.log(arr);  // 输出 ["Hello", "World!"]
      
  5. charAt(index)

    • 用途:返回指定索引位置处的字符。
    • 示例:
      const str = "Hello";
      const char = str.charAt(1);
      console.log(char);  // 输出 "e"
      
  6. charCodeAt(index)

    • 用途:返回指定索引位置处字符的 Unicode 值。
    • 示例:
      const str = "Hello";
      const code = str.charCodeAt(1);
      console.log(code);  // 输出 101
      
  7. startsWith(searchString, position)

    • 用途:判断字符串是否以指定的子串开头。可选参数 position 表示从哪个索引位置开始搜索。
    • 示例:
      const str = "Hello, World!";
      console.log(str.startsWith("Hello"));  // 输出 true
      console.log(str.startsWith("World", 7));  // 输出 true
      
  8. endsWith(searchString, length)

    • 用途:判断字符串是否以指定的子串结尾。可选参数 length 表示在指定长度范围内搜索。
    • 示例:
      const str = "Hello, World!";
      console.log(str.endsWith("!"));  // 输出 true
      console.log(str.endsWith("World", 12));  // 输出 true
      
  9. indexOf(searchValue, startIndex)

    • 用途:返回指定子串在字符串中第一次出现的索引位置。
    • 示例:
      const str = "Hello, World!";
      console.log(str.indexOf("o"));  // 输出 4
      console.log(str.indexOf("o", 5));  // 输出 8
      
  10. lastIndexOf(searchValue, startIndex)

    • 用途:返回指定子串在字符串中最后一次出现的索引位置。
    • 示例:
      const str = "Hello, World!";
      console.log(str.lastIndexOf("o"));  // 输出 8
      console.log(str.lastIndexOf("o", 7));  // 输出 4
      
  11. match(regexp)

    • 用途:使用正则表达式匹配字符串,返回匹配结果数组。如果使用了全局标志(g),将返回所有匹配项。
    • 示例:
      const str = "Hello, World!";
      console.log(str.match(/o/g));  // 输出 ["o", "o"]
      console.log(str.match(/o/));  // 输出 ["o"]
      
  12. replace(searchValue, replaceValue)

    • 用途:使用指定的字符串或正则表达式替换字符串中的匹配项。
    • 示例:
      const str = "Hello, World!";
      const newStr = str.replace("o", "x");
      console.log(newStr);  // 输出 "Hellx, World!"
      
  13. concat(string1, string2, ..., stringN)

    • 用途:连接两个或多个字符串,并返回新的字符串。
    • 示例:
      const str1 = "Hello";
      const str2 = "World";
      const newStr = str1.concat(", ", str2);
      console.log(newStr);  // 输出 "Hello, World"