在javascript中,有以下三个方法均可实现在字符串中查找指定的字符及字符串。
str.indexOf(); 此方法:查找字符在字符串对象中第一次出现的位置。存在,则返回字符串所在的位置。不存在,则返回-1。
str.lastIndexOf(); 该方法查找字符在字符串对象中最后一次出现的位置。存在,则返回字符串所在的位置。不存在,则返回-1。
str.match();访方法查找字符串中的指定字符及字符串。如果存在该字符串,则返回指定的字符串,如不存在,则返回null。
示例代码:str.indexOf();
<script>
var str="hello world!";
str.indexOf("e");
</script>
//返回的结果为:1;
示例代码:
<script>
var str="hello world!";
str.lastIndexOf("l");
</script>
//返回的结果为:9;
示例3:str.match();
<script>
var str="hello world";
str.match("world");
</script>
//返回的结果:world;