方法分类汇总索引
- 获取字符串信息方法:
length:返回字符串的长度(字符数量)
- 字符串查找方法:
charAt():返回指定索引位置的字符charCodeAt():返回指定索引位置字符的 Unicode 编码indexOf():查找子字符串首次出现的位置lastIndexOf():查找子字符串最后出现的位置includes():判断是否包含指定子字符串startsWith():判断是否以指定子字符串开头endsWith():判断是否以指定子字符串结尾
- 字符串截取/提取方法:
slice():提取字符串的一部分并返回新字符串substring():提取两个指定索引之间的字符substr():从指定位置提取指定长度的子字符串(不推荐使用)
- 字符串转换方法:
toLowerCase():将字符串转换为小写toUpperCase():将字符串转换为大写toString():返回字符串本身valueOf():返回字符串的原始值
- 字符串替换/分割方法:
replace():查找匹配子字符串并替换为新内容split():将字符串分割成字符串数组
- 字符串修剪方法:
trim():去除字符串两端的空白字符trimStart()/trimLeft():去除字符串开头的空白字符trimEnd()/trimRight():去除字符串结尾的空白字符
- 字符串重复方法:
repeat():将字符串重复指定的次数
- 字符串连接方法:
concat():连接两个或多个字符串
- 字符串填充方法:
padStart():在字符串开头填充字符至指定长度padEnd():在字符串结尾填充字符至指定长度
- 其他字符串方法:
match():查找匹配正则表达式的结果matchAll():返回所有匹配正则表达式的迭代器search():查找与正则表达式匹配的子字符串位置localeCompare():考虑区域设置比较两个字符串
以下为 JavaScript 中常用的字符串方法详解,这些方法都不会改变原字符串,而是返回一个新的字符串或其他类型的值。
一、获取字符串信息属性
1. length
- 作用:返回字符串的长度(字符数量)
- 语法:
str.length - 参数:无参数
- 返回值:数字,表示字符串的长度
- 是否改变原字符串:否
- 示例:
const str = "Hello World";
// 获取字符串长度
const len = str.length;
console.log(len); // 输出: 11
// 注意:length是属性,不是函数,不需要加括号
二、字符串查找方法
1. charAt()
- 作用:返回指定索引位置的字符
- 语法:
str.charAt(index) - 参数:
index- 必需,表示字符在字符串中的索引(从 0 开始) - 返回值:字符串,指定索引处的字符;如果索引超出范围,则返回空字符串
- 是否改变原字符串:否
- 示例:
const str = "JavaScript";
// 获取索引为4的字符
const char = str.charAt(4);
console.log(char); // 输出: 'S'
// 获取索引超出范围的字符(返回空字符串)
const invalidChar = str.charAt(20);
console.log(invalidChar); // 输出: ''
2. charCodeAt()
- 作用:返回指定索引位置字符的 Unicode 编码
- 语法:
str.charCodeAt(index) - 参数:
index- 必需,字符在字符串中的索引(从 0 开始) - 返回值:数字,表示指定索引处字符的 Unicode 编码;如果索引超出范围,则返回 NaN
- 是否改变原字符串:否
- 示例:
const str = "A";
// 获取字符 'A' 的 Unicode 编码
const code = str.charCodeAt(0);
console.log(code); // 输出: 65
// 获取索引超出范围的字符编码(返回NaN)
const invalidCode = str.charCodeAt(1);
console.log(invalidCode); // 输出: NaN
3. indexOf()
- 作用:查找某个子字符串在当前字符串中首次出现的位置
- 语法:
str.indexOf(searchValue[, fromIndex]) - 参数:
searchValue- 必需,要查找的子字符串fromIndex- 可选,开始查找的索引位置,默认为 0
- 返回值:数字,子字符串首次出现的索引;如果没有找到,则返回-1
- 是否改变原字符串:否
- 示例:
const str = "Hello, Hello World";
// 查找 "Hello" 首次出现的位置
const firstPos = str.indexOf("Hello");
console.log(firstPos); // 输出: 0
// 从索引5开始查找 "Hello"
const posFrom5 = str.indexOf("Hello", 5);
console.log(posFrom5); // 输出: 7
// 查找不存在的子字符串
const notFound = str.indexOf("JavaScript");
console.log(notFound); // 输出: -1
4. lastIndexOf()
- 作用:查找某个子字符串在当前字符串中最后出现的位置
- 语法:
str.lastIndexOf(searchValue[, fromIndex]) - 参数:
searchValue- 必需,要查找的子字符串fromIndex- 可选,开始查找的索引位置,默认为字符串的长度-1
- 返回值:数字,子字符串最后出现的索引;如果没有找到,则返回-1
- 是否改变原字符串:否
- 示例:
const str = "Hello, Hello World";
// 查找 "Hello" 最后出现的位置
const lastPos = str.lastIndexOf("Hello");
console.log(lastPos); // 输出: 7
// 在索引6之前查找 "Hello"
const posBefore6 = str.lastIndexOf("Hello", 6);
console.log(posBefore6); // 输出: 0
5. includes()
- 作用:判断当前字符串是否包含指定的子字符串
- 语法:
str.includes(searchValue[, fromIndex]) - 参数:
searchValue- 必需,要查找的子字符串fromIndex- 可选,开始查找的索引位置,默认为 0
- 返回值:布尔值,如果包含则返回 true,否则返回 false
- 是否改变原字符串:否
- 示例:
const str = "Hello World";
// 判断字符串是否包含 "World"
const hasWorld = str.includes("World");
console.log(hasWorld); // 输出: true
// 从索引6开始查找 "World"
const hasWorldFrom6 = str.includes("World", 6);
console.log(hasWorldFrom6); // 输出: true
// 判断字符串是否包含 "Java"
const hasJava = str.includes("Java");
console.log(hasJava); // 输出: false
6. startsWith()
- 作用:判断当前字符串是否以指定的子字符串开头
- 语法:
str.startsWith(searchValue[, position]) - 参数:
searchValue- 必需,要查找的子字符串position- 可选,开始查找的位置,默认为 0
- 返回值:布尔值,如果以指定子字符串开头则返回 true,否则返回 false
- 是否改变原字符串:否
- 示例:
const str = "Hello World";
// 判断字符串是否以 "Hello" 开头
const startsWithHello = str.startsWith("Hello");
console.log(startsWithHello); // 输出: true
// 判断从索引6开始的子字符串是否以 "W" 开头
const startsWithW = str.startsWith("W", 6);
console.log(startsWithW); // 输出: true
// 判断字符串是否以 "World" 开头
const startsWithWorld = str.startsWith("World");
console.log(startsWithWorld); // 输出: false
7. endsWith()
- 作用:判断当前字符串是否以指定的子字符串结尾
- 语法:
str.endsWith(searchValue[, length]) - 参数:
searchValue- 必需,要查找的子字符串length- 可选,作为字符串长度使用的值,默认为字符串的实际长度
- 返回值:布尔值,如果以指定子字符串结尾则返回 true,否则返回 false
- 是否改变原字符串:否
- 示例:
const str = "Hello World";
// 判断字符串是否以 "World" 结尾
const endsWithWorld = str.endsWith("World");
console.log(endsWithWorld); // 输出: true
// 只考虑前5个字符,判断是否以 "Hello" 结尾
const endsWithHello = str.endsWith("Hello", 5);
console.log(endsWithHello); // 输出: true
// 判断字符串是否以 "Hello" 结尾
const endsWithHelloFull = str.endsWith("Hello");
console.log(endsWithHelloFull); // 输出: false
三、字符串截取/提取方法
1. slice()
- 作用:提取字符串的一部分,并返回一个新的字符串
- 语法:
str.slice(startIndex[, endIndex]) - 参数:
startIndex- 必需,提取的起始索引(包含)endIndex- 可选,提取的结束索引(不包含),默认为字符串的长度
- 返回值:字符串,提取的子字符串
- 是否改变原字符串:否
- 示例:
const str = "Hello World";
// 提取从索引6开始到结束的子字符串
const world = str.slice(6);
console.log(world); // 输出: "World"
// 提取从索引0到5的子字符串(不包含索引5)
const hello = str.slice(0, 5);
console.log(hello); // 输出: "Hello"
// 使用负数索引(从字符串末尾开始计算)
const last3 = str.slice(-3);
console.log(last3); // 输出: "rld"
2. substring()
- 作用:提取字符串中介于两个指定索引之间的字符
- 语法:
str.substring(indexStart[, indexEnd]) - 参数:
indexStart- 必需,提取的起始索引(包含)indexEnd- 可选,提取的结束索引(不包含),默认为字符串的长度
- 返回值:字符串,提取的子字符串
- 是否改变原字符串:否
- 示例:
const str = "Hello World";
// 提取从索引0到5的子字符串
const hello = str.substring(0, 5);
console.log(hello); // 输出: "Hello"
// 如果startIndex大于endIndex,会自动交换它们
const swapped = str.substring(5, 0);
console.log(swapped); // 输出: "Hello"
// 负数索引会被视为0
const negative = str.substring(-3, 5);
console.log(negative); // 输出: "Hello"
3. substr()
- 作用:从指定位置开始提取指定长度的子字符串(注意:该方法已不推荐使用)
- 语法:
str.substr(start[, length]) - 参数:
start- 必需,提取的起始索引length- 可选,要提取的字符数,默认为到字符串的结尾
- 返回值:字符串,提取的子字符串
- 是否改变原字符串:否
- 示例:
const str = "Hello World";
// 从索引6开始提取5个字符
const world = str.substr(6, 5);
console.log(world); // 输出: "World"
// 从索引0开始提取5个字符
const hello = str.substr(0, 5);
console.log(hello); // 输出: "Hello"
// 使用负数作为起始索引(从末尾开始计算)
const last3 = str.substr(-3);
console.log(last3); // 输出: "rld"
四、字符串转换方法
1. toLowerCase()
- 作用:将字符串转换为小写
- 语法:
str.toLowerCase() - 参数:无参数
- 返回值:字符串,转换为小写的新字符串
- 是否改变原字符串:否
- 示例:
const str = "Hello World";
// 将字符串转换为小写
const lowerStr = str.toLowerCase();
console.log(lowerStr); // 输出: "hello world"
console.log(str); // 输出: "Hello World"(原字符串未改变)
2. toUpperCase()
- 作用:将字符串转换为大写
- 语法:
str.toUpperCase() - 参数:无参数
- 返回值:字符串,转换为大写的新字符串
- 是否改变原字符串:否
- 示例:
const str = "Hello World";
// 将字符串转换为大写
const upperStr = str.toUpperCase();
console.log(upperStr); // 输出: "HELLO WORLD"
console.log(str); // 输出: "Hello World"(原字符串未改变)
3. toString()
- 作用:返回字符串本身
- 语法:
str.toString() - 参数:无参数
- 返回值:字符串,与原字符串相同
- 是否改变原字符串:否
- 示例:
const str = "Hello";
// 返回字符串本身
const sameStr = str.toString();
console.log(sameStr); // 输出: "Hello"
// 对于String对象特别有用
const strObj = new String("World");
console.log(typeof strObj); // 输出: "object"
const strVal = strObj.toString();
console.log(typeof strVal); // 输出: "string"
4. valueOf()
- 作用:返回字符串的原始值
- 语法:
str.valueOf() - 参数:无参数
- 返回值:字符串,字符串的原始值
- 是否改变原字符串:否
- 示例:
// 对于字符串字面量,与原字符串相同
const str = "Hello";
console.log(str.valueOf()); // 输出: "Hello"
// 对于String对象,返回其原始值
const strObj = new String("World");
console.log(strObj.valueOf()); // 输出: "World"
console.log(typeof strObj.valueOf()); // 输出: "string"
五、字符串替换/分割方法
1. replace()
- 作用:在字符串中查找匹配的子字符串,并替换为新的子字符串
- 语法:
str.replace(regexp|substr, newSubstr|function) - 参数:
- 第一个参数:可以是字符串或正则表达式,表示要查找的内容
- 第二个参数:可以是字符串或函数,表示替换的内容
- 返回值:字符串,替换后的新字符串
- 是否改变原字符串:否
- 示例:
const str = "Hello World, Hello JavaScript";
// 替换第一个匹配的子字符串
const replacedOnce = str.replace("Hello", "Hi");
console.log(replacedOnce); // 输出: "Hi World, Hello JavaScript"
// 使用正则表达式替换所有匹配项(g表示全局匹配)
const replacedAll = str.replace(/Hello/g, "Hi");
console.log(replacedAll); // 输出: "Hi World, Hi JavaScript"
// 使用函数作为替换值
const replacedWithFunc = str.replace(/Hello/g, (match) => {
return match.toUpperCase();
});
console.log(replacedWithFunc); // 输出: "HELLO World, HELLO JavaScript"
2. split()
- 作用:将字符串分割成字符串数组
- 语法:
str.split([separator[, limit]]) - 参数:
separator- 可选,字符串或正则表达式,用于指定分割的位置limit- 可选,数字,限制返回的数组长度
- 返回值:数组,分割后的字符串数组
- 是否改变原字符串:否
- 示例:
const str = "apple,banana,orange,grape";
// 使用逗号作为分隔符
const fruits = str.split(",");
console.log(fruits); // 输出: ["apple", "banana", "orange", "grape"]
// 限制返回的数组长度为2
const limitedFruits = str.split(",", 2);
console.log(limitedFruits); // 输出: ["apple", "banana"]
// 使用空字符串作为分隔符,将每个字符作为数组元素
const chars = "hello".split("");
console.log(chars); // 输出: ["h", "e", "l", "l", "o"]
六、字符串修剪方法
1. trim()
- 作用:去除字符串两端的空白字符(包括空格、制表符、换行符等)
- 语法:
str.trim() - 参数:无参数
- 返回值:字符串,去除两端空白后的新字符串
- 是否改变原字符串:否
- 示例:
const str = " Hello World ";
// 去除两端空白
const trimmed = str.trim();
console.log(trimmed); // 输出: "Hello World"
console.log(trimmed.length); // 输出: 11(原长度为17)
2. trimStart() / trimLeft()
- 作用:去除字符串开头(左侧)的空白字符
- 语法:
str.trimStart()或str.trimLeft() - 参数:无参数
- 返回值:字符串,去除开头空白后的新字符串
- 是否改变原字符串:否
- 示例:
const str = " Hello World ";
// 去除左侧空白
const trimmedStart = str.trimStart();
console.log(trimmedStart); // 输出: "Hello World "
console.log(trimmedStart.length); // 输出: 14(原长度为17)
// trimLeft是trimStart的别名
const trimmedLeft = str.trimLeft();
console.log(trimmedLeft); // 输出: "Hello World "
3. trimEnd() / trimRight()
- 作用:去除字符串结尾(右侧)的空白字符
- 语法:
str.trimEnd()或str.trimRight() - 参数:无参数
- 返回值:字符串,去除结尾空白后的新字符串
- 是否改变原字符串:否
- 示例:
const str = " Hello World ";
// 去除右侧空白
const trimmedEnd = str.trimEnd();
console.log(trimmedEnd); // 输出: " Hello World"
console.log(trimmedEnd.length); // 输出: 14(原长度为17)
// trimRight是trimEnd的别名
const trimmedRight = str.trimRight();
console.log(trimmedRight); // 输出: " Hello World"
七、字符串重复方法
1. repeat()
- 作用:将字符串重复指定的次数
- 语法:
str.repeat(count) - 参数:
count- 必需,数字,表示重复的次数(0 到正无穷大之间的整数) - 返回值:字符串,重复指定次数后的新字符串
- 是否改变原字符串:否
- 示例:
const str = "Hi";
// 重复3次
const repeated = str.repeat(3);
console.log(repeated); // 输出: "HiHiHi"
// 重复0次,返回空字符串
const empty = str.repeat(0);
console.log(empty); // 输出: ""
// 重复次数为负数会报错
try {
str.repeat(-1);
} catch (e) {
console.log(e); // 输出: RangeError: Invalid count value
}
八、字符串连接方法
1. concat()
- 作用:连接两个或多个字符串
- 语法:
str.concat(str1[, str2[, ...[, strN]]]) - 参数:
str1, str2, ..., strN- 要连接的字符串 - 返回值:字符串,连接后的新字符串
- 是否改变原字符串:否
- 示例:
const str1 = "Hello";
const str2 = " ";
const str3 = "World";
// 连接多个字符串
const result = str1.concat(str2, str3, "!");
console.log(result); // 输出: "Hello World!"
// 与使用 + 运算符效果相同
const sameResult = str1 + str2 + str3 + "!";
console.log(sameResult); // 输出: "Hello World!"
九、字符串填充方法
1. padStart()
- 作用:在字符串的开头填充指定的字符,直到达到指定的长度
- 语法:
str.padStart(targetLength[, padString]) - 参数:
targetLength- 必需,数字,目标字符串的长度padString- 可选,用于填充的字符串,默认为空格
- 返回值:字符串,填充后的新字符串
- 是否改变原字符串:否
- 示例:
const str = "5";
// 填充到长度为3,使用默认空格填充
const padded = str.padStart(3);
console.log(padded); // 输出: " 5"
// 填充到长度为5,使用"0"填充
const zeroPadded = str.padStart(5, "0");
console.log(zeroPadded); // 输出: "00005"
// 如果目标长度小于原字符串长度,则返回原字符串
const shorter = str.padStart(1);
console.log(shorter); // 输出: "5"
2. padEnd()
- 作用:在字符串的结尾填充指定的字符,直到达到指定的长度
- 语法:
str.padEnd(targetLength[, padString]) - 参数:
targetLength- 必需,数字,目标字符串的长度padString- 可选,用于填充的字符串,默认为空格
- 返回值:字符串,填充后的新字符串
- 是否改变原字符串:否
- 示例:
const str = "5";
// 填充到长度为3,使用默认空格填充
const padded = str.padEnd(3);
console.log(padded); // 输出: "5 "
// 填充到长度为5,使用"0"填充
const zeroPadded = str.padEnd(5, "0");
console.log(zeroPadded); // 输出: "50000"
// 使用多个字符进行填充
const multiChar = "Hi".padEnd(7, "abc");
console.log(multiChar); // 输出: "Hiabcab"(循环使用填充字符串)
十、其他字符串方法
1. match()
- 作用:在字符串中查找匹配正则表达式的结果
- 语法:
str.match(regexp) - 参数:
regexp- 必需,正则表达式对象 - 返回值:数组,包含匹配结果;如果没有找到匹配,则返回 null
- 是否改变原字符串:否
- 示例:
const str = "The quick brown fox jumps over the lazy dog";
// 查找所有以字母"o"开头的单词
const matches = str.match(/o\w+/g);
console.log(matches); // 输出: ["ox", "over", "og"]
// 查找第一个匹配项的详细信息
const firstMatch = str.match(/q\w+/);
console.log(firstMatch);
// 输出: ["quick", index: 4, input: "The quick brown fox jumps over the lazy dog", groups: undefined]
// 没有找到匹配项
const noMatch = str.match(/z\w+/);
console.log(noMatch); // 输出: null
2. matchAll()
- 作用:返回一个包含所有匹配正则表达式的结果及分组捕获的迭代器
- 语法:
str.matchAll(regexp) - 参数:
regexp- 必需,正则表达式对象(必须包含全局标志 g) - 返回值:迭代器,包含所有匹配结果
- 是否改变原字符串:否
- 示例:
const str = "Hello 123, Hello 456";
const regex = /Hello (\d+)/g;
// 获取所有匹配结果的迭代器
const matches = str.matchAll(regex);
// 将迭代器转换为数组
const results = Array.from(matches);
console.log(results);
// 输出: [
// ["Hello 123", "123", index: 0, input: "Hello 123, Hello 456", groups: undefined],
// ["Hello 456", "456", index: 11, input: "Hello 123, Hello 456", groups: undefined]
// ]
3. search()
- 作用:查找与正则表达式相匹配的子字符串的位置
- 语法:
str.search(regexp) - 参数:
regexp- 必需,正则表达式对象 - 返回值:数字,第一个匹配项的索引;如果没有找到匹配,则返回-1
- 是否改变原字符串:否
- 示例:
const str = "Hello World";
// 查找第一个大写字母的位置
const upperPos = str.search(/[A-Z]/);
console.log(upperPos); // 输出: 0
// 查找"World"的位置
const worldPos = str.search(/World/);
console.log(worldPos); // 输出: 6
// 查找不存在的模式
const noPos = str.search(/Java/);
console.log(noPos); // 输出: -1
4. localeCompare()
- 作用:比较两个字符串,考虑当前区域设置
- 语法:
str.localeCompare(compareString[, locales[, options]]) - 参数:
compareString- 必需,要比较的字符串locales- 可选,指定区域设置options- 可选,配置比较选项
- 返回值:数字,表示比较结果(-1:当前字符串在前;0:相等;1:当前字符串在后)
- 是否改变原字符串:否
- 示例:
const str1 = "apple";
const str2 = "banana";
// 比较两个字符串
console.log(str1.localeCompare(str2)); // 输出: -1("apple" 在 "banana" 之前)
console.log(str2.localeCompare(str1)); // 输出: 1("banana" 在 "apple" 之后)
console.log(str1.localeCompare("apple")); // 输出: 0(相等)
// 考虑地区的比较(德语中 "ä" 被视为 "a" 的变音)
console.log("ä".localeCompare("z", "de")); // 输出: -1
console.log("ä".localeCompare("z", "sv")); // 输出: 1(在瑞典语中 "ä" 排在 "z" 之后)
喜欢的话,留下你的评论吧~