JavaScript 只有indexOf方法,可以用来确定一个字符串是否包含在另一个字符串中。
includes():
startsWith():
endsWith():
返回布尔值,表示参数字符串是否在原字符串的尾部。
let str = "hello world"
str.includes('hello',1)
str.startsWith('hello',1)
str.endsWith('world',10)
这三个都可以带参数
endsWith 的参数表示前X个字符, 其他两个表示从第X个字符开始查找
字符串拼接
const name = '小明';
const score = 59;
const result = `${name}的考试成绩${score > 60?'':'不'}及格`;
repeat()重复字符串
let str = "hello world"
str.repeat(3) //hello worldhello worldhello world
padStart()、padEnd()字符串补全
padStart()用于头部补全,padEnd()用于尾部补全。
'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'
'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'
//第一个参数表示补全的最大长度,第二个表示用于补全的字符串
trimStart()、trimEnd()消除字符串空格
trimStart()消除字符串头部的空格,trimEnd()消除尾部的空格
let str =" aa-bb-cc "
str.trimStart()//'aa-bb-cc '
str.trimEnd() //' aa-bb-cc'
replace()字符串替换 、replaceAll()
let str ="aa-bb-cc"
str.replace( '-' ,'/') 替换一次
str.replaceAll( '-' ,'/') 全部替换