js中判斷一個字符串是否包含另一個字符串的方式
字符串的方法
方法一 indexOf() 推薦
var str = '123';
console.log(str.indexOf('2') !== -1); //true
indexOf()返回一個字符串在另一個字符串首次出現的位置,有的話返回索引,沒有返回-1
方法二 match()
var str = '123';
var reg = new RegExp('/3/');
console.log(str.match(reg)); //true
match()可以在一個字符串內檢索制定的值,或找到一個或多個正則表達式的匹配
方法三 search()
var str = '123';
console.log(str.search(’2‘) !== -1); //true
search()用于檢索字符串中指定的子字符串,或檢索與正則表達式相匹配的子字符串,如果沒找到任何相匹配的子串,則返回-1
利用正則的方法
方法四 test()
var str = '123';
var reg = new RegExp(/3/);
console.log(reg.test(str)); //true
test()用于檢索字符串中指定的值,返回true或false
方法五 exec()
var str = '123';
var reg = new RegExp(/3/);
console.log(reg.exec(str)); //true
exec()用于檢索字符串中的正則表達式的匹配,返回匹配的結果,一個數組,如果沒匹配到,返回null
es6新增的方式
includes()返回布爾值
表示是否找到了參數字符串
startsWith()返回布爾值
表示參數字符串是否出現在指定字符串的開頭
endWith()返回布爾值
表示參數字符串是否出現在指定字符串的末尾
var str = 'hello world!';
console.log(str.includes('o')); //true
console.log(str.startsWith('hello')); //true
console.log(str.endWith('!')); //true
參數說明
這三個方法都支持第二個參數,表示開始搜索的位置
includes(),startsWith()表示從第幾個開始;
endWith()表示前多少個字符
var str = 'hello world!';
console.log(str.includes('o',3)); //true
console.log(str.startsWith('hello',3)); //false
console.log(str.endWith('!',3)); //false
str.repeat(n)返回一個新串,表示將原字符串重復n次
var str = 'hello';
var cloneStr = str.repeat(3);
console.log(cloneStr); //hellohellohello