营销网站seo推广网站模版asp
EasyClick JavaScript 字符串进阶
在 JavaScript 中,字符串是最常用的数据类型之一。以下是 JavaScript 字符串的常用方法,涵盖了字符串操作的各种场景。
基本查询方法
length- 获取字符串长度
const str = "Hello, World!";
console.log(str.length); // 13
charAt()- 获取指定位置的字符
console.log(str.charAt(0)); // "H"
console.log(str.charAt(7)); // "W"
charCodeAt()- 获取字符的 Unicode 编码
console.log(str.charCodeAt(0)); // 72 (H 的 Unicode)
indexOf()- 查找子字符串首次出现的位置
console.log(str.indexOf("World")); // 7
console.log(str.indexOf("world")); // -1 (区分大小写)
lastIndexOf()- 查找子字符串最后一次出现的位置
const text = "Hello, World! Hello!";
console.log(text.lastIndexOf("Hello")); // 14
includes()- 检查是否包含子字符串
console.log(str.includes("World")); // true
console.log(str.includes("world")); // false
startsWith()- 检查是否以指定字符串开头
console.log(str.startsWith("Hello")); // true
console.log(str.startsWith("hello")); // false
endsWith()- 检查是否以指定字符串结尾
console.log(str.endsWith("!")); // true
console.log(str.endsWith("World")); // false
字符串操作方法
concat()- 连接字符串
const str1 = "Hello";
const str2 = "World";
console.log(str1.concat(", ", str2, "!")); // "Hello, World!"
slice()- 提取子字符串
console.log(str.slice(0, 5)); // "Hello" (0到5,不包括5)
console.log(str.slice(7)); // "World!" (从7到结尾)
console.log(str.slice(-6)); // "World!" (从末尾开始)
substring()- 提取子字符串(类似 slice)
console.log(str.substr(7, 5)); // "World" (从7开始,取5个字符)
split()- 分割字符串为数组
const words = str.split(", ");
console.log(words); // ["Hello", "World!"]const chars = str.split("");
console.log(chars); // ["H", "e", "l", "l", "o", ",", " ", "W", "o", "r", "l", "d", "!"]
repeat()- 重复字符串
console.log("abc".repeat(3)); // "abcabcabc"
字符串修改方法
toLowerCase()- 转换为小写
console.log(str.toLowerCase()); // "hello, world!"
toUpperCase()- 转换为大写
console.log(str.toUpperCase()); // "HELLO, WORLD!"
trim()- 去除两端空白
const spaced = " Hello, World! ";
console.log(spaced.trim()); // "Hello, World!"
trimStart()/ trimLeft()- 去除开头空白
console.log(spaced.trimStart()); // "Hello, World! "
trimEnd()/ trimRight()- 去除结尾空白
console.log(spaced.trimEnd()); // " Hello, World!"
replace()- 替换字符串
console.log(str.replace("World", "JavaScript")); // "Hello, JavaScript!"
replaceAll()- 替换所有匹配项
const text = "apple, banana, apple";
console.log(text.replaceAll("apple", "orange")); // "orange, banana, orange"
正则表达式相关方法
match()- 匹配正则表达式
const email = "user@example.com";
const matchResult = email.match(/[a-z]+@[a-z]+\.[a-z]{2,3}/);
console.log(matchResult); // ["user@example.com"]
matchAll()- 匹配所有结果
const text = "test1 test2 test3";
const matches = [...text.matchAll(/test(\d)/g)];
console.log(matches);
// [
// ["test1", "1"],
// ["test2", "2"],
// ["test3", "3"]
// ]
search()- 搜索匹配位置
console.log(str.search("World")); // 7
console.log(str.search(/world/i)); // 7 (不区分大小写)
