Search for all instances of a string inside a string

前端 未结 5 1140
情深已故
情深已故 2020-12-15 08:43

Hello I am using indexOf method to search if a string is present inside another string. But I want to get all the locations of where string is? Is there any method to get al

5条回答
  •  盖世英雄少女心
    2020-12-15 09:13

    Here is a working function:

    function allIndexOf(str, toSearch) {
        var indices = [];
        for(var pos = str.indexOf(toSearch); pos !== -1; pos = str.indexOf(toSearch, pos + 1)) {
            indices.push(pos);
        }
        return indices;
    }
    

    Use example:

    > allIndexOf('dsf dsf kfvkjvcxk dsf', 'dsf');
    [0, 4, 18]
    

提交回复
热议问题