在字符串中檢索字符的幾種方式,供大家參考,具體內容如下
var text="abcdefgh你好,很高興認識你!"; var str1="abc"; var str2="def"; var str3="ABC"; var str4="很高興"; function isContain(str,substr){ return new RegExp(substr).test(str); } console.log(isContain(text,str1));//true console.log(isContain(text,str4));//true console.log(text.indexOf(str1));//0,如果匹配則返回其位置 console.log(text.indexOf(str2));//3 console.log(text.indexOf(str4));//11 console.log(text.indexOf(str3));//-1,如果不匹配則返回-1 console.log(text.indexOf(str1,1));//-1 第二個參數表示從下標為1的地方開始找 console.log(text.lastIndexOf(str1,1));//0,從后向前檢索,返回其下標 console.log(text.lastIndexOf(str2));//3 console.log(text.substring(0,5)); //abcde 提取下標之間的字符串,包括第一個參數,不包括第二個參數 console.log(text.slice(0,5));//abcde 根substring作用基本相同 console.log(text.substr(0,3));//abc,第一個參數表示起始下標,第二個參數表示獲取的字符長度 console.log(text.match(str1));//返回abc數組,可以使用正則,進行了解 console.log(text.match(str1)[0]);//abc以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答