Search for all instances of a string inside a string

前端 未结 5 1121
情深已故
情深已故 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 08:54

    Here's a regex way to do it:

    function positions(str, text) {
      var pos = [], regex = new RegExp("(.*?)" + str, "g"), prev = 0;
      text.replace(regex, function(_, s) {
        var p = s.length + prev;
        pos.push(p);
        prev = p + str.length;
      });
      return pos;
    }
    
    0 讨论(0)
  • 2020-12-15 09:07

    Try something like:

    var regexp = /abc/g;
    var foo = "abc1, abc2, abc3, zxy, abc4";
    var match, matches = [];
    
    while ((match = regexp.exec(foo)) != null) {
      matches.push(match.index);
    }
    
    console.log(matches);
    
    0 讨论(0)
  • 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]
    
    0 讨论(0)
  • 2020-12-15 09:14

    You can use indexOf('searchstring', ), using the index returned 'last time round' + 1 until you get -1 back.

    0 讨论(0)
  • 2020-12-15 09:15

    I don't know if there's a built in function to do it. You could do it in a simple loop though:

    function allIndexes(lookIn, lookFor) {
        var indices = new Array();
        var index = 0;
        var i = 0;
        while(index = lookIn.indexOf(lookFor, index) > 0) {
            indices[i] = index;
            i++;
        }
        return indices;
    }
    
    0 讨论(0)
提交回复
热议问题