「前端每日一问(15)」JavaScript 字符串的常用方法有哪些?

374 阅读5分钟

本题难度:⭐

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

答:

image.png

操作方法

可以从增、删、改、查的维度去总结。

字符串一旦创建就不可更改,下面的所有增删改方法都不会改变原字符串,都是返回一个新的字符串

一般用字符串拼接

// 字符串拼接
const str1 = 'lin'
const str2 = 'handsome'

str1 + ' is ' + str2 // 'lin is handsome'
`${str1} is ${str2}` // 'lin is handsome'

当然,+ 或者 `` 不是字符串的方法,如果要用方法的话可以用 concat,这个方法不常用,但还是介绍下吧。

concat

concat() 方法将一个或多个字符串与原字符串连接合并,形成一个新的字符串并返回。

// 语法
str.concat(str2, [, ...strN])
const str1 = 'lin'
const str2 = 'handsome'

str1.concat(' is ').concat(str2) // 'lin is handsome'
// 很显然,不如字符串拼接用着方便。
const greetList = ['Hello', ' ', 'Venkat', '!']
''.concat(...greetList) // 'Hello Venkat!'

greetList.join('') // 'Hello Venkat!'
// 这种情况下也不如用数组的 join 方法。

  • slice
  • substring

slice

slice() 方法提取某个字符串的一部分,并返回一个新的字符串,接收一或两个参数。

返回的新字符串由参数indexStart 和 indexEnd 决定(包括 indexStart,indexEnd)。

只传入一个参数,indexEnd 默认为字符串长度。

如果参数为负数,则等同于 index + strLength

const str = 'hello world!'
str.slice(0, 4)   // 'hell'
str.slice(2)      // 'llo world'
str.slice(-5, -1) // 'worl'  等同于 str.slice(6, 10)
str.slice(6, 10)  // 'worl'

substring

substring() 方法和 slice 方法的功能差不多,只是截取字符串的规则有些小区别,

  • 如果 indexStart 等于 indexEnd,substring 返回一个空字符串。
  • 如果省略 indexEnd,substring 提取字符一直到字符串末尾。
  • 如果任一参数大于 strLength,则被当作 strLength。
  • 如果 indexStart 大于 indexEnd,则 substring 的执行效果就像两个参数调换了一样。(与 slice 不同)
  • 如果任一参数小于 0 或为 NaN,则被当作 0。(与 slice 不同)
const str = 'hello world'

str.slice(4, 4)        // ''
str.substring(4, 4)    // ''

str.slice(2)           // 'llo world'
str.substring(2)       // 'llo world'

str.slice(4, 100)      // 'o world'
str.substring(4, 100)  // 'o world'

str.slice(4, 2)        // ''
str.substring(4, 2)    // 'll'

str.slice(4, -2)       // 'o wor'
str.substring(4, -2)   // 'hell'

还有一个 substr 方法,已经快被废弃了,不要使用,详见 mdn

  • trim
  • repeat
  • padEnd
  • toLowerCase、 toUpperCase

trim

trim() 方法会从一个字符串的两端删除空白字符。

trimStart() 方法从字符串的开头删除空格。trimLeft() 是此方法的别名。

trimEnd()  方法从一个字符串的末端移除空白字符。trimRight() 是这个方法的别名。

const str = '   hello world!    '

str.trim()      // 'hello world!'
str.trimLeft()  // 'hello world!    '
str.trimRight()  // '   hello world!'

repeat

接收一个参数 n,表示要将字符串复制 n 次,然后返回拼接所有副本后的字符串,n 会被自动转成整数。

const str = 'abc'
str.repeat(-1)     // RangeError: repeat count must be positive and less than inifinity
str.repeat(0)      // ''
str.repeat(1)      // 'abc'
str.repeat(2)      // 'abcabc'
str.repeat(3.5)    // 'abcabcabc' 参数count将会被自动转换成整数.
str.repeat(1/0)    // RangeError: repeat count must be positive and less than inifinity

padEnd、padStart

padEnd() 方法会用一个字符串填充当前字符串(如果需要的话则重复填充),返回填充后达到指定长度的字符串。从当前字符串的末尾(右侧)开始填充。

padStart() 方法从左侧填充

const str = 'hello'

str.padEnd(10, '.')  // 'hello.....'
str.padStart(10, '.')  // '.....hello'

toLowerCase、 toUpperCase

大小写转化

const str = '中文简体 zh-CN || zh-Hans'
str.toLowerCase()  // '中文简体 zh-cn || zh-hans'
const str = 'hello'
str.toUpperCase()  // 'HELLO'

  • chatAt()
  • indexOf、lastIndexOf
  • includes、startsWith、endsWith

charAt

charAt()  方法从一个字符串中返回指定下标的字符。

const str = 'hello'

str.charAt(1)  // 'e'

indexOf、lastIndexOf

indexOf() 方法从字符串开头去搜索传入的字符串,并返回位置。lastIndexOf() 方法是从后面往前面找。

const str = 'hello'

str.indexOf('e')     // 1
str.indexOf('l')     // 2  有重复元素,就返回第一个
str.indexOf('xx')    // -1 如果没找到,则返回 -1
str.lastIndexOf('l') // 3

includes、startsWith、endsWith

includes() 方法用于判断一个字符串是否包含在另一个字符串中,根据情况返回 true 或 false。

startsWith() 方法用来判断当前字符串是否以另外一个给定的子字符串开头。

endWith() 方法则判断当前字符串是否以另外一个给定的子字符串结尾。

const str = 'hello, nice to meet you'

str.includes('nice')     // true
str.startsWith('hello')  // true
str.endsWith('you')      // true

转换方法

split

split() 方法把字符串按照指定的分割符,拆分成数组中的每一项。

const str = 'Paul,Booker,Ayton,Bridges,Johnson'
str.split(',') // ['Paul', 'Booker', 'Ayton', 'Bridges', 'Johnson']

正则表达式方法

针对正则表达式,字符串设计了几个方法

  • match()
  • search()
  • replace()

match

match() 方法检索返回一个字符串匹配正则表达式的结果。

match() 方法接收一个参数,可以是一个正则表达式字符串,也可以是一个RegExp对象,返回数组。

const str = 'find, mind, wind'
const pattern = /.ind/g
const matches = str.match(pattern)
console.log(matches) // ['find', 'mind', 'wind']

search

search()  方法执行正则表达式和字符串之间的一个搜索匹配。找到则返回匹配索引,否则返回 -1。

const str = 'find, mind, wind'
str.search(/ind/) // 1
str.search(/xx/) // -1

replace

接收两个参数,第一个参数为匹配的内容,第二个参数为替换的元素(可用函数)

const str = 'find, mind, wind'
str.replace('ind', 'abc') // 'fabc, mind, wind'  只会替代找到的第一个
str.replace(/ind/g, 'abc') // 'fabc, mabc, wabc' 替代全部

结尾

如果我的文章对你有帮助,你的👍就是对我最大的支持^_^

我是阿林,输出洞见技术,再会!

上一篇:

「前端每日一问(14)」JavaScript 中如何中断 forEach 循环?

下一篇:

「前端每日一问(16)」深拷贝和浅拷贝的区别?