1.检测字符串中是否包含着另一个字符串
indexOf(),startsWith(),endsWith(),includes()
let s='hello world!';
//检测参数字符串是否在源字符串中,并返回参数字符串位置
console.log(s.indexOf('l'))//true
//表示参数字符串是否在源字符串的头部,返回布尔值
console.log(s.startsWith('hello'))//true
console.log(s.startsWith('ello'))//false
//表示参数字符串是否在源字符串的尾部,返回布尔值
console.log(s.endsWith('!'));//true
console.log(s.endsWith('d'));//false
//表示参数字符串是否在源字符串中,返回布尔值
console.log(s.includes('o'));//true
console.log(s.includes('h'));//true
以上三种新方法都支持第二个参数,表示开始搜索的位置;
startsWith(),includes() 第二参数与参数字符串第一个字符的位置要相对应,否则false;
endsWith()从n开始不包含n的位置向前检索也就是从n-1的位置检索,如果n-1的位置不是该参数字符就返回false;
let s='hello world!';
//表示参数字符串是否在源字符串的头部,返回布尔值
console.log(s.startsWith('hello',6))//false 从第6个字符开始向后查找参数字符串,结果显示没有 false
console.log(s.startsWith('ello',1))//true 从第2个字符向后查找 ,检索到参数字符串,返回true
console.log(s.startsWith('llo',1))//false 从第2个字符向后查找 ,因为第二参数与参数字符串第一个字符在源字符串中的位置不相等,返回false。
//表示参数字符串是否在源字符串中,返回布尔值
console.log(s.includes('o',6));//true
console.log(s.includes('l',0));//true
//表示参数字符串是否在源字符串的尾部,返回布尔值
//从n开始不包含n的位置向前检索也就是从n-1的位置检索,如果n-1的位置不是该参数字符就返回false;
console.log(s.endsWith('h',2));//true
console.log(s.endsWith('d',6));//false
2.字符串的复制函数;repeat()函数;
console.log('x'.repeat(3));//xxx x被重复三次
//如果参数是小数,会自动取整
console.log('x'.repeat(3.9));//xxx x还是重复三次
//如果参数小于等于-1或者是Infinity,会报错
console.log('x'.repeat(-1));//Invalid count value
console.log('x'.repeat(Infinity));//Invalid count value
//如果参数在0到-1之间,或者NaN,或者不能被转换成数值得的字符串,就等同于0,
console.log('x'.repeat(-0.8));//''空
console.log('x'.repeat(NaN));//''空
console.log('x'.repeat('N'));//''空
console.log('x'.repeat('3'));//xxx 字符串可以转换为数值
console.log('x'.repeat('3g'));//''空
3.字符串补全
1.头部补全用 padStart();
2.尾部补全用 padEnd();
3.两者共有两个参数,第一个参数是字符串最小长度,第二个参数用来补全的字符串;
//最小长度5,源字符串不够最小长度,补上两个补全字符串,
//一个在头部补全,一个在尾部补全;
console.log('x'.padStart(5,'ab'))//ababx
console.log('x'.padEnd(5,'ab'))//xabab
//如果补全字符串与源字符串相加的长度超出了最小长度,呢么就截取补全字符串相对应的源字符串长度
console.log('x'.padStart(4,'ab'))//abax
console.log('x'.padEnd(4,'ab'))//xaba
//如果省略第二个参数,那么就用空格来作为补全字符串
console.log('x'.padStart(4))// x,
console.log('x'.padEnd(4))//x ,
//常用的情景就是数值补0;
console.log('1'.padStart(2,'0'))//01
console.log('1'.padEnd(2,'0'))//10
4.字符串模板
1.使用 “反引号标识
2.变量使用${},可以引用对象
具体可以参考阮一峰老师的ES6入门,字符串扩展一节ES6入门