034 js常用字符串方法

83 阅读2分钟
  1. length:获取字符串的长度。 例如:"hello".length; // 输出 5
  2. charAt(index):返回指定索引处的字符。 例如:"hello".charAt(1); // 输出 "e"
  3. concat(str):连接两个字符串并返回新的字符串。 例如:"hello".concat(" world"); // 输出 "hello world"
  4. indexOf(substr, [start]):从一个字符串中搜索指定子串,并返回第一个匹配项的索引;如果未找到,则返回-1。 例如:"hello world".indexOf("world"); // 输出 6
  5. lastIndexOf(substr, [start]):从一个字符串中反向搜索指定子串,并返回最后一个匹配项的索引;如果未找到,则返回-1。 例如:"hello world world".lastIndexOf("world"); // 输出 12
  6. slice(start, [end]):截取一个字符串的一部分,并返回新的字符串。参数为起始索引(包含)和结束索引(不包含)。 例如:"hello world".slice(0, 5); // 输出 "hello"
  7. substring(start, [end]):截取一个字符串的一部分,并返回新的字符串。参数为起始索引(包含)和结束索引(不包含),自动调整较小值作为起始索引。 例如:"hello world".substring(0, 5); // 输出 "hello"
  8. substr(start, [length]):截取一个字符串的一部分,并返回新的字符串。参数为起始索引(包含)和指定长度。 例如:"hello world".substr(0, 5); // 输出 "hello"
  9. replace(regexp/substr, newSubstr/function):替换字符串中匹配的子串或正则表达式,返回新的字符串。 例如:"hello world".replace("world", "GPT-4"); // 输出 "hello GPT-4"
  10. toLowerCase():将字符串转换为小写字母形式,并返回结果。 例如:"Hello World".toLowerCase(); // 输出 "hello world"
  11. toUpperCase():将字符串转换为大写字母形式,并返回结果。 例如:"Hello World".toUpperCase(); // 输出 "HELLO WORLD"
  12. trim():去除字符串两端的空白字符,并返回结果。 例如:" hello world ".trim(); // 输出 "hello world"