JS中字符串的常用方法

  • charAt(index) - 返回在指定位置的字符。
const str = 'Hello';  
console.log(str.charAt(1)); // 输出 'e'
  • concat(string2, string3, …, stringX) - 连接两个或更多的字符串,并返回新的字符串。
const str1 = 'Hello, ';  
const str2 = 'World!';  
console.log(str1.concat(str2)); // 输出 'Hello, World!'
  • indexOf(searchValue[, fromIndex]) - 返回某个指定的字符串值在字符串中首次出现的位置。
const str = 'Hello, World!';  
console.log(str.indexOf('World')); // 输出 7
  • lastIndexOf(searchValue[, fromIndex]) - 返回某个指定的字符串值最后出现的位置。
const str = 'Hello, World, World!';  
console.log(str.lastIndexOf('World')); // 输出 13
  • replace(searchValue, replaceValue) - 在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。
const str = 'Hello, World!';  
console.log(str.replace('World', 'JavaScript')); // 输出 'Hello, JavaScript!'
  • slice(startIndex, endIndex) - 提取字符串的片断,并在新的字符串中返回被提取的部分。
const str = 'Hello, World!';  
console.log(str.slice(7, 12)); // 输出 'World'
  • split(separator, limit) - 把字符串分割为字符串数组。
const str = 'apple,banana,orange';  
console.log(str.split(',')); // 输出 ['apple', 'banana', 'orange']
  • substring(indexStart, indexEnd) - 提取字符串中两个指定的索引号之间的字符。
const str = 'Hello, World!';  
console.log(str.substring(7, 12)); // 输出 'World'
  • toLowerCase() - 把字符串转换为小写。
const str = 'HELLO, WORLD!';  
console.log(str.toLowerCase()); // 输出 'hello, world!'
  • toUpperCase() - 把字符串转换为大写。
const str = 'hello, world!';  
console.log(str.toUpperCase()); // 输出 'HELLO, WORLD!'
  • trim() - 移除字符串两侧的空白符或其他预定义字符。
const str = '   Hello, World!   ';  
console.log(str.trim()); // 输出 'Hello, World!'
  • match(regexp) - 检索字符串中指定的值。返回结果数组。
const str = 'Hello, World!';  
const regex = /World/;  
console.log(str.match(regex)); // 输出 ['World']

slice和substring的区别
参数差异:
substring(start, end): substring() 方法接受两个参数,start(起始索引)和 end(结束索引)。这两个参数都是必需的,但可以是负数。如果任一参数小于0或非数值,则它会被当作0。此外,substring() 的 end 参数表示子字符串的最后一个字符之后的索引,因此它实际上是排除的。
slice(start, end): slice() 方法也接受两个参数,start 和 end。与 substring() 不同,slice() 的参数可以是负数,表示从字符串的末尾开始计算。如果任一参数被省略,slice() 会使用默认值:如果省略 start,则从索引0开始;如果省略 end,则直到字符串的末尾。
越界处理:
如果 substring() 的 start 大于 end,则它会交换这两个参数的位置。这意味着 substring(2, 1) 将返回从索引1到索引2的子字符串(不包括索引2),即空字符串。
slice() 的行为与此不同。如果 start 大于 end,slice() 将返回一个空字符串,不会交换参数。
对负数的处理:
substring() 将负数参数当作0处理。
slice() 将负数参数从字符串的末尾开始计数。例如,slice(-2) 将从字符串的倒数第二个字符开始,直到字符串的末尾。

let str = 'Hello, world!';  
  
console.log(str.substring(2, 7)); // 输出 "llo, "  
console.log(str.slice(2, 7));     // 输出 "llo, "  
  
console.log(str.substring(-2));   // 输出 "Hello, world!"  
console.log(str.slice(-2));       // 输出 "d!"  
  
console.log(str.substring(2, 1)); // 输出 "e"  
console.log(str.slice(2, 1));     // 输出 ""  
  
console.log(str.substring(7, 2)); // 输出 "llo,"  
console.log(str.slice(7, 2));     // 输出 ""

你可能感兴趣的:(JavaScript,javascript,前端)