字符串查找
str.indexOf(searchValue[, fromIndex])
以前用indexOf来查找字符串是否存在,并返回索引位置,当不存在时返回-1。
例:
let str = 'How are you';
console.log(str.indexOf('no')) // -1
此时我们就根据这个返回值是否为-1来判断字符串是否存在,
当然为了简便,我们也会用二进制取反的方式来判断。
例:
// 等于-1的方法
console.log(str.indexOf('no') === -1) // true
// 二进制取反的方法
// 取反原理:位置索引值为0-n的正整数,不存在为-1,
// 而0-n的正整数二进制取反为一个非零数,-1取反则为0(在js中,0会转换成false)
console.log(~str.indexOf('no')) // 0
str.includes(searchString[, position])
现在es6出现了includes,可直接用来判断字符串是否存在了。
例:
console.log(str.includes('no')) // false
是不是方便很多呢。
字符串检测
当我们需要检测某字符串是否以xxx开头或结尾时用,我们以前怎么用的啊?要么用indexOf,要么用正则吧!现在可以用以下两种来检测了。
str.startsWith(searchString[, position])
判断该字符串是否以searchString开头(可以用来检测是否是地址)。
例:
let str = 'http://www.baidu.com';
console.log(str.startsWith('http://')); // true
str.endsWith(searchString[, length])
判断该字符串是否以searchString结尾(可以用来检测文件扩展名)。
例:
let str = './images/icon/login.png';
console.log(str.endsWith('.png')); // true
另外
还有一些其他方法,暂时用得比较少的,比如:
// 复制当前字符串,count次数
str.repeat(count);
// 往字符串前面填充字符串
// targetLength 目标字符串长度, padString要填充的字符串
str.padStart(targetLength [, padString]);
// 往字符串后面填充字符串
// targetLength 目标字符串长度, padString要填充的字符串
str.padEnd(targetLength [, padString]);
注:爱护原创,转载请说明出处