Search for all instances of a string inside a string

前端 未结 5 1122
情深已故
情深已故 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;
    }
    

提交回复
热议问题