JavaScript字符串检索字符的几种方式

作者:木棉

时间:2026-10-22

浏览:661

本文介绍在JavaScript中检索字符串的几种方式,包括使用正则表达式、indexOf、substr和match方法。通过示例代码展示各方法的用法和返回值,帮助读者理解不同场景下的字符串检索技巧。

文章目录

JavaScript字符串检索方法

本文介绍在JavaScript中检索字符串的几种方式,包括使用正则表达式、indexOf、substr和match方法。


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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章