Javascript Data Type How to - Find all indexes of a specified character within a string








Question

We would like to know how to find all indexes of a specified character within a string.

Answer


<!DOCTYPE html>
<html>
<body>
<script type='text/javascript'>
<!--from www .j  a  v  a 2s . co  m-->
    var str = "scissors";
    var indices = [];
    for(var i=0; i<str.length;i++) {
        if (str[i] === "s") indices.push(i+1);
    }
    document.writeln(indices);

</script>
</body>
</html>

The code above is rendered as follows: