JavaScript字符串检索字符的几种方式
作者:木棉时间:2026-10-22 05:02:10浏览:660
本文介绍在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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。
作者最新文章
JS合并多个数组的三种方法:concat、spread与flat
2026-11-05 17:39:45
JavaScript怎么准确判断数据类型:typeof、instanceof与Object.prototype.toString
2026-11-05 17:09:21
JS中将数组和对象混合组装为JSON字符串
2026-11-05 16:41:42
JS运算符优先级与结合性的区别是什么?
2026-11-05 13:22:02
JS Map怎么只遍历Key或Value
2026-11-05 13:00:36
