字符串查找
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]);
注:愛護原創,轉載請說明出處