根据字符返回位置

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Document</title>
</head>
<body>
字符串:<input type="text" id="input1">
索引的字符串:<input type="text" id="input2">
<button id="btn1">从前面开始索引</button>
<button id="btn2">从后面开始索引</button>
</body>
<script>
    //根据字符返回位置,索引号都是从前面开始
    //从前面开始索引
    function $id(id) {return document.getElementById(id);}
    $id("btn1").onclick=function()
    {
        alert( $id("input1").value.indexOf($id("input2").value)); //2
    }
    //从后面开始索引
    $id("btn2").onclick=function()
    {
        alert($id("input1").value.lastIndexOf($id("input2").value));//8
    }
</script>
</html>

  

原文地址:https://www.cnblogs.com/shanlu0000/p/11228698.html