JavaScript 面试题
目录

JavaScript 中字符串的常用方法有哪些?

· 约 7 分钟读完 · 第 303 / 507 章

推荐答案

在 JavaScript 中,字符串的常用方法包括:

  • charAt(index):返回指定索引位置的字符。
  • concat(str1, str2, ...):连接两个或多个字符串。
  • includes(searchString, position):判断字符串是否包含指定的子字符串。
  • indexOf(searchValue, fromIndex):返回指定子字符串首次出现的索引。
  • lastIndexOf(searchValue, fromIndex):返回指定子字符串最后一次出现的索引。
  • match(regexp):返回字符串匹配正则表达式的结果。
  • replace(searchValue, replaceValue):替换字符串中的子字符串。
  • slice(startIndex, endIndex):提取字符串的一部分并返回新字符串。
  • split(separator, limit):将字符串分割为数组。
  • substring(startIndex, endIndex):提取字符串的一部分并返回新字符串。
  • toLowerCase():将字符串转换为小写。
  • toUpperCase():将字符串转换为大写。
  • trim():去除字符串两端的空白字符。
  • trimStart() 或 trimLeft():去除字符串开头的空白字符。
  • trimEnd() 或 trimRight():去除字符串结尾的空白字符。
  • startsWith(searchString, position):判断字符串是否以指定的子字符串开头。
  • endsWith(searchString, length):判断字符串是否以指定的子字符串结尾。
  • repeat(count):返回重复指定次数的字符串。

本题详细解读

charAt(index)

charAt 方法返回字符串中指定索引位置的字符。如果索引超出范围,则返回空字符串。

concat(str1, str2, ...)

concat 方法用于连接两个或多个字符串,并返回新的字符串。

includes(searchString, position)

includes 方法用于判断字符串是否包含指定的子字符串,返回布尔值。

indexOf(searchValue, fromIndex)

indexOf 方法返回指定子字符串首次出现的索引,如果未找到则返回 -1。

lastIndexOf(searchValue, fromIndex)

lastIndexOf 方法返回指定子字符串最后一次出现的索引,如果未找到则返回 -1。

match(regexp)

match 方法用于在字符串中查找与正则表达式匹配的结果,返回一个数组。

replace(searchValue, replaceValue)

replace 方法用于替换字符串中的子字符串,返回新的字符串。

slice(startIndex, endIndex)

slice 方法用于提取字符串的一部分并返回新字符串。

split(separator, limit)

split 方法用于将字符串分割为数组。

substring(startIndex, endIndex)

substring 方法用于提取字符串的一部分并返回新字符串。

toLowerCase()

toLowerCase 方法将字符串转换为小写。

toUpperCase()

toUpperCase 方法将字符串转换为大写。

trim()

trim 方法用于去除字符串两端的空白字符。

trimStart() 或 trimLeft()

trimStart 或 trimLeft 方法用于去除字符串开头的空白字符。

trimEnd() 或 trimRight()

trimEnd 或 trimRight 方法用于去除字符串结尾的空白字符。

startsWith(searchString, position)

startsWith 方法用于判断字符串是否以指定的子字符串开头,返回布尔值。

endsWith(searchString, length)

endsWith 方法用于判断字符串是否以指定的子字符串结尾,返回布尔值。

repeat(count)

repeat 方法用于返回重复指定次数的字符串。