JavaScript字符串检索字符的方法
在字符串中检索字符的几种方式,供大家参考,具体内容如下
vartext="abcdefgh你好,很高兴认识你!";
varstr1="abc";
varstr2="def";
varstr3="ABC";
varstr4="很高兴";
functionisContain(str,substr){
returnnewRegExp(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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短