在JavaScript中,字符串是一种原始数据类型,同时也是一个对象。因此,字符串对象具有一些内置的方法,可以用于处理和操作字符串数据。以下是一些常见的JavaScript字符串方法,并为每个方法提供一个简单的使用案例:
length 属性 - 获取字符串长度
const text = "Hello, World!";
const length = text.length;
console.log(length); // Output: 13
索引访问和切片
const text = "Hello, World!";
console.log(text[0]); // Output: 'H'
console.log(text.slice(7, 12)); // Output: 'World'
indexOf() 和 lastIndexOf() 方法 - 查找子字符串的索引
const text = "Hello, World!";
console.log(text.indexOf("World")); // Output: 7
console.log(text.lastIndexOf("o")); // Output: 7 (last occurrence of 'o')
startsWith() 和 endsWith() 方法 - 检查字符串开头和结尾
const text = "Hello, World!";
console.log(text.startsWith("Hello")); // Output: true
console.log(text.endsWith("World!")); // Output: false
toLowerCase() 和 toUpperCase() 方法 - 转换大小写
const text = "Hello, World!";
console.log(text.toLowerCase()); // Output: "hello, world!"
console.log(text.toUpperCase()); // Output: "HELLO, WORLD!"
trim() 方法 - 去除开头和结尾的空白字符
const text = " Hello, World! ";
console.log(text.trim()); // Output: "Hello, World!"
replace() 方法 - 替换子字符串
const text = "Hello, World!";
const newText = text.replace("Hello", "Hi");
console.log(newText); // Output: "Hi, World!"
split() 方法 - 拆分字符串为数组
const text = "apple,banana,orange";
const fruitsArray = text.split(",");
console.log(fruitsArray); // Output: ['apple', 'banana', 'orange']
charAt() 方法 - 获取指定索引处的字符
const text = "Hello, World!";
console.log(text.charAt(0)); // Output: 'H'
console.log(text.charAt(7)); // Output: 'W'
includes() 方法 - 检查字符串是否包含指定子字符串
const text = "Hello, World!";
console.log(text.includes("World")); // Output: true
console.log(text.includes("hello")); // Output: false (case-sensitive)
charCodeAt() 方法 - 获取指定索引处字符的Unicode值
const text = "Hello, World!";
console.log(text.charCodeAt(0)); // Output: 72