String类型在javascript实际开发中常用的一些操作方法总结
JavaScript 中的 String
类型提供了许多内置的方法,这些方法在日常开发中非常有用。下面列举了一些常用的字符串操作方法及其简单示例:
1. length
获取字符串长度。
let str = "Hello World";
console.log(str.length); // 输出 11
2. charAt(index)
返回指定索引处的字符。
let str = "Hello";
console.log(str.charAt(1)); // 输出 e
3. charCodeAt(index)
返回指定索引处字符的 Unicode 编码。
let str = "Hello";
console.log(str.charCodeAt(0)); // 输出 72
4. concat(string1, string2, ...stringN)
将一个或多个字符串连接到原字符串上并返回新的字符串。
let str = "Hello";
let result = str.concat(" ", "World");
console.log(result); // 输出 Hello World
5. toLowerCase()
转换字符串为小写。
let str = "HELLO";
console.log(str.toLowerCase()); // 输出 hello
6. toUpperCase()
转换字符串为大写。
let str = "hello";
console.log(str.toUpperCase()); // 输出 HELLO
7. indexOf(searchValue[, fromIndex])
返回首次出现指定值searchValue
的位置索引,如果没有找到则返回 -1。此外,可以通过可选参数 fromIndex
来指定搜索的起始位置。
参数说明:
searchValue
:要查找的子字符串或字符。fromIndex
:可选参数,指定开始搜索的位置,默认为 0。
const str = "Hello, world! Welcome to the JavaScript world.";// 查找 "world" 首次出现的位置
console.log(str.indexOf("world")); // 输出 7// 从索引 10 开始查找 "world"
console.log(str.indexOf("world", 10)); // 输出 40// 查找不存在的子字符串
console.log(str.indexOf("universe")); // 输出 -1// 区分大小写
console.log(str.indexOf("hello")); // 输出 -1// 指定的位置超过了字符串的长度
console.log(str.indexOf("Hello", 55)); // 输出 -1// 指定的位置是负数,则会按照 0 来处理
console.log(str.indexOf("world", -10)); // 输出 7
8. lastIndexOf(searchValue[, fromIndex])
与 indexOf
类似,但是从字符串的末尾开始查找。
参数说明:
searchValue
:要查找的子字符串或字符。fromIndex
:可选参数,指定开始反向搜索的位置,默认为字符串的长度。这意味着默认情况下,搜索将从字符串的末尾开始。
const str = "Welcome to the JavaScript world. JavaScript is fun!";// 查找 "JavaScript" 最后一次出现的位置
console.log(str.lastIndexOf("JavaScript")); // 输出 33// 从索引 20 开始查找 "JavaScript"
console.log(str.lastIndexOf("JavaScript", 20)); // 输出 15// 查找不存在的子字符串
console.log(str.lastIndexOf("universe")); // 输出 -1// 区分大小写
console.log(str.lastIndexOf("javascript")); // 输出 -1// 指定的位置超过了字符串的长度,lastIndexOf() 会从字符串末尾开始搜索
console.log(str.lastIndexOf("JavaScript", 55)); // 输出 33// 指定的位置是负数,则返回 -1
console.log(str.lastIndexOf("JavaScript", -10)); // 输出 -1
9. includes(searchValue[, fromIndex])
检查字符串是否包含指定的子字符串,包含返回 true,否则返回 false。此方法还可以接受一个可选的参数 ·fromIndex·,用于指定搜索的开始位置。
参数说明:
searchValue
:要查找的子字符串或字符。fromIndex
:可选参数,指定开始搜索的位置,默认为 0。如果fromIndex
是负数,那么它会被当作 0 处理。
const str = "Welcome to the JavaScript world. JavaScript is fun!";
const str2 = "hello";// 检查字符串是否包含 "JavaScript"
console.log(str.includes("JavaScript")); // 输出 true// 从索引 20 开始查找 "JavaScript"
console.log(str.includes("JavaScript", 20)); // 输出 true// 从索引 35 开始查找 "JavaScript"
console.log(str.includes("JavaScript", 35)); // 输出 false// 查找不存在的子字符串
console.log(str.includes("universe")); // 输出 false// 区分大小写
console.log(str.includes("javascript")); // 输出 false// 指定的位置超过了字符串的长度,includes() 会从字符串的末尾开始搜索,实际上不会找到任何匹配项,所以会返回 false。
console.log(str.includes("JavaScript", 55)); // 输出 false// 指定的位置是负数,则会被当作 0 处理,即从字符串的开头开始搜索。
console.log(str.includes("JavaScript", -10)); // 输出 true// 如果 searchValue 是空字符串(""),includes() 总是返回 true,因为每个字符串都包含空字符串。
console.log(str.includes("")); // 输出 true
// 即使hello中没有空格 也会返回true
console.log(str2.includes("")); // 输出 true
10. startsWith(searchValue[, position])
检查字符串是否以指定的子字符串开头,是则返回 true,否则返回 false。此方法还可以接受一个可选的参数 position,用于指定从字符串中的哪个位置开始比较。
参数说明:
searchValue
:要查找的子字符串或字符。position
:可选参数,指定开始比较的位置,默认为 0。如果position
是负数,它会被当作 0 处理。
const str = "Welcome to the JavaScript world. JavaScript is fun!";// 检查字符串是否以 "Welcome" 开头
console.log(str.startsWith("Welcome")); // 输出 true// 从索引 8 开始查找 "to the"
console.log(str.startsWith("to the", 8)); // 输出 true// 从索引 7 开始查找 "to the"
console.log(str.startsWith("to the", 7)); // 输出 false// 查找不存在的子字符串
console.log(str.startsWith("tothe")); // 输出 false// 区分大小写
console.log(str.startsWith("To the")); // 输出 false// 如果 position 超过了字符串的长度,startsWith() 会返回 false,因为没有足够的字符来进行比较。
console.log(str.startsWith("to the", 55)); // 输出 falseconsole.log(str.length);// 如果 position 是负数,它会被当作 0 处理,即从字符串的开头开始比较。
console.log(str.startsWith("to the", -10)); // 输出 false// 如果 searchValue 是空字符串(""),startsWith() 总是返回 true,因为每个字符串都可以被认为是空字符串的前缀。
console.log(str.startsWith("")); // 输出 true
11. endsWith(searchValue[, length])
检查字符串是否以指定的子字符串结尾,是则返回 true,否则返回 false。此方法还可以接受一个可选的参数 length,用于指定从字符串的开始位置到该位置的子字符串,从而检查这个子字符串是否以 searchValue
结尾。
参数说明:
searchValue
:要查找的子字符串或字符。length
:可选参数,指定结束比较的位置。如果省略,则会检查整个字符串是否以searchValue
结尾。如果提供了length
参数,则会检查从字符串的开始位置到length
指定的位置之间的子字符串是否以searchValue
结尾。注意,length
参数表示的是字符串的长度,而不是索引位置。
const str = "Welcome to the JavaScript world. JavaScript is fun!";// 检查字符串是否以 "fun!" 结尾
console.log(str.endsWith("fun!")); // 输出 true// 检查字符串是否以 "JavaScript is fun!" 结尾
console.log(str.endsWith("JavaScript is fun!")); // 输出 true// 检查字符串的前半部分是否以 "JavaScript" 结尾
console.log(str.endsWith("JavaScript", 31)); // 输出 true// 检查字符串的前半部分是否以 "JavaScript" 结尾(从位置 30 开始)
console.log(str.endsWith("JavaScript", 30)); // 输出 false// 查找不存在的子字符串
console.log(str.endsWith("hello")); // 输出 false// 区分大小写
console.log(str.endsWith("javaScript")); // 输出 false// 如果 length 参数大于或等于字符串的实际长度,则 endsWith() 会检查整个字符串是否以 searchValue 结尾。
console.log(str.endsWith("JavaScript", 55)); // 输出 falseconsole.log(str.length);// 如果 length 参数小于 searchValue 的长度,那么 endsWith() 返回 false,因为没有足够的字符来匹配 searchValue。
console.log(str.endsWith("JavaScript", 9)); // 输出 false// 如果 searchValue 是空字符串(""),endsWith() 总是返回 true,因为每个字符串都可以被认为是空字符串的后缀。
console.log(str.endsWith("")); // 输出 true
12. slice(start[, end])
方法提取字符串的一部分,并将其作为新字符串返回,而不修改原始字符串。
参数说明:
start
:可选参数,表示开始截取的位置。如果省略,则默认从索引 0 开始。end
:可选参数,表示结束截取的位置(不包括 end 位置本身)。如果省略,则一直截取到字符串的末尾。
const str = "Hello, world! Welcome to the JavaScript world.";console.log(str.length);// 截取从索引 0 到 5 的子字符串
console.log(str.slice(0, 6)); // 输出 "Hello,"// 截取从索引 7 到字符串末尾的子字符串
console.log(str.slice(7)); // 输出 "world! Welcome to the JavaScript world."// 截取从索引 7 到 12 的子字符串
console.log(str.slice(7, 13)); // 输出 "world!"// 截取从字符串末尾的第 7 个字符到末尾的子字符串
console.log(str.slice(-7)); // 输出 " world."// 截取从字符串末尾的第 12 个字符到末尾的第 7 个字符的子字符串。如果 start 或 end 是负数,那么它会根据字符串的长度被转换成一个正数索引,即 -1 表示字符串的最后一个字符,-2 表示倒数第二个字符,以此类推。
console.log(str.slice(-12, -7)); // 输出 "cript "// 当 start 大于 end 时,会返回一个空字符串。
console.log(str.slice(10, 7)); // 输出 ""
13. substring(start[, end])
substring()
方法是 JavaScript 字符串对象(String)的一个方法,用于从原字符串中截取一部分并返回一个新的字符串。与 slice()
方法类似,substring()
方法也不会修改原字符串,而是返回一个新的字符串副本。
参数说明:
start
:可选参数,表示开始截取的位置。如果省略,则默认从索引 0 开始。end
:可选参数,表示结束截取的位置(不包括 end 位置本身)。如果省略,则一直截取到字符串的末尾。
const str = "Hello, world! Welcome to the JavaScript world.";// 截取从索引 0 到 5 的子字符串
console.log(str.substring(0, 6)); // 输出 "Hello,"// 截取从索引 7 到字符串末尾的子字符串
console.log(str.substring(7)); // 输出 "world! Welcome to the JavaScript world."// 截取从索引 7 到 12 的子字符串
console.log(str.substring(7, 13)); // 输出 "world!"// 当 start 大于 end 时,会自动交换参数
console.log(str.substring(13, 7)); // 输出 "world!"// 当 start 或 end 为负数时,按 0 处理
console.log(str.substring(-5, 10)); // 输出 "Hello, wor"
14. substr(start[, length])
从字符串的指定位置开始截取指定长度的字符串。
参数说明:
start
:必需参数,表示开始截取的位置。如果 start 是负数,那么它会根据字符串的长度被转换成一个正数索引。length
:可选参数,表示要截取的字符数量。如果省略,则一直截取到字符串的末尾。
const str = "Hello, world! Welcome to the JavaScript world.";console.log(str.length); // 46// 截取从索引 0 开始的 6 个字符
console.log(str.substr(0, 6)); // 输出 "Hello,"// 截取从索引 7 开始到字符串末尾的所有字符
console.log(str.substr(7)); // 输出 "world! Welcome to the JavaScript world."// 截取从索引 7 开始的 6 个字符
console.log(str.substr(7, 6)); // 输出 "world!"// 如果 start 是负数,那么它会根据字符串的长度被转换成一个正数索引。例如,-1 表示字符串的最后一个字符,-2 表示倒数第二个字符,以此类推
console.log(str.substr(-7, 6)); // 输出 " world"// 当 start 超过字符串长度时,substr() 会返回一个空字符串。
console.log(str.substr(50, 5)); // 输出 ""// 当 length 为负数时,substr() 会将其当作 0 处理。
console.log(str.substr(5, -5)); // 输出 ""// 超出了剩余的字符串长度,substr() 会截取到字符串的末尾。
console.log(str.substr(18, 60)); // 输出 "ome to the JavaScript world."
15. split(separator[, limit])
根据指定的分隔符将字符串分割成数组。返回一个新的数组,其中包含了由 separator 分割后的字符串片段。
参数说明:
separator
:必需参数,表示用于分割字符串的分隔符。它可以是一个字符串或正则表达式。如果 separator 是一个正则表达式,可以使用正则表达式的特殊符号来实现更复杂的分割。limit
:可选参数,表示结果数组的最大长度。如果设置了 limit 并且分割会产生更多的子字符串,那么多余的子字符串将被丢弃,结果数组的最后一个元素将是剩余的所有子字符串的组合。
const str = "Hello, world! Welcome to the JavaScript world.";// 使用逗号作为分隔符
console.log(str.split(',')); // 输出 ['Hello', ' world! Welcome to the JavaScript world.']// 使用感叹号作为分隔符
console.log(str.split('!')); // 输出 ['Hello, world', ' Welcome to the JavaScript world.']// 如果 separator 不存在于字符串中,则返回的数组只有一个元素,即原始字符串本身。
console.log(str.split('$')); // 输出 ['Hello, world! Welcome to the JavaScript world.']// 使用空格作为分隔符,并限制结果数组的长度为 2
console.log(str.split(' ', 2)); // 输出 ['Hello,', 'world!']// 如果 limit 设置为 0 ,split() 方法会返回一个空数组。
console.log(str.split(' ', 0)); // 输出 []// 如果 limit 设置为负数,split() 方法会使用空格作为分隔符。
console.log(str.split(' ', -2)); // 输出 ['Hello,', 'world!', 'Welcome', 'to', 'the', 'JavaScript', 'world.']// 在字符串的开头或结尾出现,那么结果数组的第一个或最后一个元素将为空字符串。
console.log(str.split('H')); // 输出 ['', 'ello, world! Welcome to the JavaScript world.']
console.log(str.split('.')); // 输出 ['Hello, world! Welcome to the JavaScript world', '']// 使用正则表达式作为分隔符,分割所有非字母数字字符
console.log(str.split(/\W+/)); // 输出 ['Hello', 'world', 'Welcome', 'to', 'the', 'JavaScript', 'world', '']// 如果 separator 是一个空字符串(""),那么 split() 方法将会把原字符串分割成单个字符组成的数组。
console.log(str.split('')); // 输出 ['H', 'e', 'l', 'l', 'o',..., '.']
16. replace(searchValue | regex, replaceValue)
替换字符串中的某个值或符合正则表达式的部分。
参数说明:
searchValue
:必需参数,表示要被替换的子字符串或正则表达式。replaceValue
:必需参数,表示用来替换 searchValue 的新子字符串或一个回调函数。如果是字符串,则直接替换;如果是函数,则函数返回的值将用于替换。
// 使用字符串作为 searchValue
const str = "Hello, world! Welcome to the JavaScript world.";
console.log(str.replace("world", "universe")); // 输出 "Hello, universe! Welcome to the JavaScript world."// 使用正则表达式作为 searchValue
console.log(str.replace(/world/g, "universe")); // 输出 "Hello, universe! Welcome to the JavaScript universe."// 使用带有标志的正则表达式
const str2 = "123-456-7890";
console.log(str2.replace(/\d/g, "*")); // 输出 "***-***-****"// 使用函数作为replaceValue
const str3 = "The price is 100 dollars.";
console.log(str3.replace(/\d+/g, function(match) {return parseInt(match) * 1.1;
})); // 输出 "The price is 110.00000000000001 dollars."const str4 = "The quick brown fox jumps over the lazy fox.";
console.log(str4.replace(/fox/g, function(match, offset, string) {console.log(`Match: ${match}, Offset: ${offset}, String: ${string}`);return match.toUpperCase();
})); // 输出 "The quick brown FOX jumps over the lazy FOX."
17. trim()
去除字符串两端的空白字符。
let str = " Hello World ";
console.log(str.trim()); // 输出 "Hello World"
18. padStart(targetLength[, padString])
在字符串的开头填充指定的字符,直到达到目标长度。返回一个新的字符串,该字符串的长度至少为 targetLength,并在必要时在开头添加了 padString
参数说明:
targetLength
:必需参数,表示最终字符串的目标长度。padString
:可选参数,表示用于填充的字符串。如果省略,则默认使用空格 (" " ) 作为填充字符。
// 使用指定字符串作为填充字符
let str = "5";
console.log(str.padStart(4, "0")); // 输出 "0005"// 当原始字符串长度超过目标长度时不进行填充
const str2 = "HelloWorld";
console.log(str2.padStart(5, 'xx')); // 输出 "HelloWorld"
19. padEnd(targetLength[, padString])
在字符串的结尾填充指定的字符,直到达到目标长度。参数同padStart
。
let str = "5";
console.log(str.padEnd(4, "0")); // 输出 "5000"
这些方法是 JavaScript 字符串操作中最基本且最常用的方法之一。了解并熟练掌握它们将有助于你在实际开发中更高效地处理字符串数据。