JavaScript 只有indexOf方法,可以用来确定一个字符串是否包含在另一个字符串中。

includes():

返回布尔值,表示是否找到了参数字符串。

startsWith():

返回布尔值,表示参数字符串是否在原字符串的头部。

endsWith():

返回布尔值,表示参数字符串是否在原字符串的尾部。

  1. let str = "hello world"
  2. str.includes('hello'1)
  3. str.startsWith('hello'1)
  4. str.endsWith('world'10)

这三个都可以带参数
endsWith 的参数表示前X个字符, 其他两个表示从第X个字符开始查找

字符串拼接

  1. const name = '小明';
  2. const score = 59;
  3. const result = `${name}的考试成绩${score > 60?'':'不'}及格`;

repeat()重复字符串

  1. let str = "hello world"
  2. str.repeat(3) //hello worldhello worldhello world

padStart()、padEnd()字符串补全

padStart()用于头部补全,padEnd()用于尾部补全。

  1. 'x'.padStart(5, 'ab') // 'ababx'
  2. 'x'.padStart(4, 'ab') // 'abax'
  3. 'x'.padEnd(5, 'ab') // 'xabab'
  4. 'x'.padEnd(4, 'ab') // 'xaba'
  5. //第一个参数表示补全的最大长度,第二个表示用于补全的字符串

trimStart()、trimEnd()消除字符串空格

trimStart()消除字符串头部的空格,trimEnd()消除尾部的空格

  1. let str =" aa-bb-cc "
  2. str.trimStart()//'aa-bb-cc '
  3. str.trimEnd() //' aa-bb-cc'

replace()字符串替换 、replaceAll()

  1. let str ="aa-bb-cc"
  2. str.replace( '-' ,'/') 替换一次
  3. str.replaceAll( '-' ,'/') 全部替换