JS中操作字符串的属性和方法(20个)

81 阅读2分钟

在JavaScript中,有很多方法和属性可用于操作字符串,先来20个开胃小菜吧。

  1. length 属性:返回字符串的长度。
const str = "Hello";
console.log(str.length); // 输出 5
  1. charAt() 方法:返回指定索引位置的字符。
const str = "Hello";
console.log(str.charAt(0)); // 输出 "H"
  1. concat() 方法:连接两个或多个字符串。
const str1 = "Hello";
const str2 = " World";
console.log(str1.concat(str2)); // 输出 "Hello World"
  1. indexOf() 方法:返回字符串中第一次出现指定字符的索引。
const str = "Hello World";
console.log(str.indexOf("o")); // 输出 4
  1. lastIndexOf() 方法:返回字符串中最后一次出现指定字符的索引。
const str = "Hello World";
console.log(str.lastIndexOf("o")); // 输出 7
  1. slice() 方法:提取字符串的一部分并返回一个新字符串。
const str = "Hello World";
console.log(str.slice(6, 11)); // 输出 "World"
  1. substring() 方法:提取字符串的一部分并返回一个新字符串,类似于 slice(),但不允许负数索引。
const str = "Hello World";
console.log(str.substring(6, 11)); // 输出 "World"
  1. substr() 方法:从指定位置开始提取字符串的指定数量字符并返回一个新字符串。
const str = "Hello World";
console.log(str.substr(6, 5)); // 输出 "World"
  1. toLowerCase() 方法:将字符串转换为小写。
const str = "Hello World";
console.log(str.toLowerCase()); // 输出 "hello world"
  1. toUpperCase() 方法:将字符串转换为大写。
const str = "Hello World";
console.log(str.toUpperCase()); // 输出 "HELLO WORLD"
  1. trim() 方法:去除字符串两端的空格。
const str = "   Hello World   ";
console.log(str.trim()); // 输出 "Hello World"
  1. split() 方法:将字符串拆分为字符串数组,根据指定的分隔符进行拆分。
const str = "Hello,World";
console.log(str.split(",")); // 输出 ["Hello", "World"]
  1. replace() 方法:将字符串中的指定字符替换为新的字符。
const str = "Hello World";
console.log(str.replace("World", "JavaScript")); // 输出 "Hello JavaScript"
  1. startsWith() 方法:判断字符串是否以指定字符开头。
const str = "Hello World";
console.log(str.startsWith("Hello")); // 输出 true
  1. endsWith() 方法:判断字符串是否以指定字符结尾。
const str = "Hello World";
console.log(str.endsWith("World")); // 输出 true
  1. includes() 方法:判断字符串是否包含指定字符。
const str = "Hello World";
console.log(str.includes("o

")); // 输出 true
  1. charAt() 方法:返回指定索引位置的字符。
const str = "Hello";
console.log(str.charAt(0)); // 输出 "H"
  1. charCodeAt() 方法:返回指定索引位置字符的 Unicode 值。
const str = "Hello";
console.log(str.charCodeAt(0)); // 输出 72
  1. match() 方法:在字符串中搜索指定的模式,并返回所有匹配的字符串数组。
const str = "Hello World";
console.log(str.match(/o/g)); // 输出 ["o", "o"]
  1. repeat() 方法:将字符串重复指定次数并返回一个新字符串。
const str = "Hello";
console.log(str.repeat(3)); // 输出 "HelloHelloHello"