JavaScript 内置对象 String 的常用方法

654 阅读4分钟

这是我参与8月更文挑战的第11天,活动详情查看:8月更文挑战

JavaScript 内置对象 String 的常用方法

创建字符串

  • var str = "hello world";

获取字符串长度

  • str.length

charAt()

  • 用途:获取字符串指定索引的字符
  • 语法:str.charAt(index)
  • index 取值为 0str.length - 1,不支持负数
  • 参考:String.prototype.charAt()
  • 使用示例:
var str = 'hello'
console.log(str.charAt(0))  // h
  • 注意:如果不写 index,则默认 index0
  • 与索引操作 [] 对比,索引访问不到会返回 undefined,而 charAt 返回一个空字符串。也就是说,charAt 总是返回一个字符串。

indexOf()

  • 用途:获取给定字符串在当前字符串中第一次出现的索引,如果找不到,返回 -1
  • 语法:str.indexOf(searchValue [, fromIndex])
  • searchValue 是待查找的字符串。
  • 参考:String.prototype.indexOf()
  • 示例:
console.log('hello world'.indexOf('w'))  // 6

'hello world'.indexOf('')  // 0

lastIndexOf()

  • 用途:从后往前查找,获取给定字符串在当前字符串中第一次出现的索引,如果找不到,返回 -1
  • 语法:str.lastIndexOf(searchValue[, fromIndex])
  • 参考:String.prototype.lastIndexOf()
  • 示例:
var str = 'Brave new world'
console.log(str.lastIndexOf('new'))  // 6

includes()

  • 用途:判断当前字符串是否包含给定字符串
  • 语法:str.includes(searchString[, position])
  • searchString 为待查找的字符串
  • position 为从 str 的哪个索引位置开始搜寻子字符串,默认值为 0
  • 参考:String.prototype.includes()
  • 示例:
// includes 区分大小写
'Blue Whale'.includes('blue'); // returns false

startsWith()

  • 用途:判断当前字符串是否已给定字符串开头
  • 语法:str.startsWith(searchString[, position])
  • position 为起始搜索位置
  • 参考String.prototype.startsWith()
  • 示例:
// startsWith 区分大小写
var str = 'hello'
console.log(str.startsWith('Hell'))  // false

endsWith()

  • 用途:判断当前字符串是否以给定字符串结尾
  • 语法:str.endsWith(searchString[, length])
  • lengthstr 的长度,默认值为 str.length
  • 参考:String.prototype.endsWith()
  • 示例:
var str = 'hello'
console.log(str.endsWith('llo'))  // true

// length 用于指定字符串长度,相当于不含该字符串的索引
var str = "To be, or not to be, that is the question.";

alert( str.endsWith("question.") );  // true
alert( str.endsWith("to be") );      // false
alert( str.endsWith("to be", 19) );  // true


padStart()

  • 用途:从左边开始,使用给定字符串填充当前字符串,使得最终长度达到指定长度,超出的部分将被截断。
  • 语法:str.padStart(targetLength [, padString])
  • padString 默认为空格 ' '
  • 参考:String.prototype.padStart()
  • 示例:
console.log('abc'.padStart(10, 'nihao'))  //  nihaoniabc

padEnd()

  • 用途:从右边开始,使用给定字符串填充当前字符串,使得最终长度达到指定长度,超出的部分将被截断。
  • 语法:``
  • 参考:String.prototype.padEnd()
  • 示例:
console.log('abc'.padEnd(8, '*'))  // abc*****

repeat()

  • 用途:重复当前字符串给定的次数,返回新字符串。
  • 语法:str.repeat(count)
  • 如果不给出 countcount 默认为 0
  • 如果 count0,则返回一个空字符串
  • 参考:String.prototype.repeat()
  • 示例:
'abc'.repeat()  // ''
'abc'.repeat(0)  // ''
'abc'.repeat(2)  // 'abcabc'
// 3.7 被自动截断为 3
'abc'.repeat(3.7)  // 'abcabcabc'

concat()

  • 用途:拼接一个或多个字符串,返回新的字符串
  • 语法:str.concat(str2, [, ...strN])
  • 性能:强烈建议使用 ++= 代替 concat 方法
  • 参考:String.prototype.concat()
  • 示例:
''.concat(1, 2, 3)  // '123'
'hello'.concat(' ', 'world')  // 'hello world'

replace()

  • 用途:将当前字符串中的旧字符串替换成新字符串,仅替换第一个匹配项,返回一个全新的字符串
  • 语法:str.replace(regexp|substr, newSubStr|function)
  • 参考:String.prototype.replace()
  • 示例:
var str = 'apple'
var newStr = str.replace('apple', 'pear')
console.log(newStr)  // pear

search()

  • 用途:在当前字符串中查找给定字符串第一次出现的索引
  • 语法:str.search(regexp)
  • regexp 是一个正则表达式对象,如果传入了非正则表达式,则会使用 new RegExp(regexp)
  • 参考:String.prototype.search()
  • 示例:
console.log('hello'.search('el'))  // 1

split()

  • 用途:根据分割符和切割次数把当前字符串拆分成数组并返回
  • 语法:str.split([separator[, limit]])
  • 如果不传参数,将返回具有原始字符串的数组。如果 seperator'',将返回由单个字符组成的数组。这个方法跟 Pythonstr.split() 不太一样,Python 中默认按照空白字符来切割。
  • limit 表示返回数组的最大长度(Python 中字符串的 split() 方法,第二个参数 maxsplit 表示最大切割次数)
  • 参考:String.prototype.split()
  • 示例:
var str = 'hello world'
var arr = str.split('o')
console.log(arr)  // ['hell', 'w', 'rld']

substr()substring()

  • 用途:从当前字符串中截取子串
  • 注意:substr() 是遗留函数,尽可能使用 substring() 代替它
  • substr() 的语法:str.substr(start[, length]),有点类似于 C 语言的 substr(pos, len) 函数。
  • substring() 的语法:str.substring(indexStart[, indexEnd]),截取的时候不包括 indexEnd 索引对应的字符
  • 参考:String.prototype.substr()
  • 参考:String.prototype.substring()
  • 示例:
'hello'.substring(1, 3)  // 'el'

toLowerCase()

'Abc'.toLowerCase()  // abc

toUpperCase()

'Abc'.toUpperCase()  // ABC

trim()

  • 用途:去掉当前字符串两边的空白字符,返回新的字符串
  • 语法:str.trim()
  • 参考:String.prototype.trim()
  • 示例:
'\t\nfoo  \n'.trim()
'foo'