jQuery Data Type How to - Get the positions of the substrings








Question

We would like to know how to get the positions of the substrings.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--  www.j  a  v a2  s  .co  m-->
var str = 'foo bar foo baz foo';
var getPositions = function (find, str) {
    var arr = [],
        pos = 0,
        flen = find.length,
        len = str.length, i;
    while (pos < len) {
        i = str.indexOf(find, pos);
        if (i !== -1) {
            arr.push(i);
            pos = i + flen;
        } else {
            return arr.length ? arr : false;
        }
    }
    return arr.length ? arr : false;
};
document.write(getPositions('foo', str));

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

The code above is rendered as follows: