当前位置:编程学习 > JS >>

javascript 查找字符串中最后一次出现字符或字符串

在js中要实现查找字符串中最后一次出现字符或字符串我们可以用到lastIndexOf() 方法

string.lastIndexOf(string, num)
    string.lastIndexOf(string)

lastIndexOf() 方法可返回一个指定的字符串值最后出现的位置,在一个字符串中的指定位置从后向前搜索

<html>
    <script language="JavaScript">
    <!--
    var myString = new String("Hello World, here I am!");
    document.write(myString.lastIndexOf("e") + '<br>');

    document.write(myString.lastIndexOf("l", 3));

    document.close();

    -->

    </script>


</html>

提示和注释
注释:lastIndexOf() 方法对大小写敏感!

注释:如果要检索的字符串值没有出现,则该方法返回 -1。


实例
在本例中,我们将在 "Hello world!" 字符串内进行不同的检索:

<script type="text/网页特效">

var str="Hello world!"
document.write(str.lastIndexOf("Hello") + "<br />")
document.write(str.lastIndexOf("World") + "<br />")
document.write(str.lastIndexOf("world"))

</script>以上代码的输出:

0
-1
6

补充:网页制作,js教程
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,