-1

I can't find out a solution to the following problem and it's driving me nuts. I need to find every position of a string within another string.

This is what I have come up with:

function getMatchIndices(regex, str) {
    let result = [];
    let match;
    let regex = new RegExp(regex, 'g');
    while (match = regex.exec(str))
        result.push(match.index);
    return result;
}


const line = "aabaabbaababaababaaabaabaaabaabbabaababa";
const rule = 'aba';

const indices = getMatchIndices(new RegExp(rule, "g"), line);

console.log(indices);

Now, the issue is that this does NOT match aba's that are formed in the middle of two other matches...

Here is an image illustrating the problem:

Image

Any ideas?

  • I agree that your question is a duplicate, unless you really need to allow for your "rule" to be a regex, rather than just a string. – Brian Stephens May 23 '19 at 18:53

1 Answers1

2

I realize this is NOT a Regex solution. So it might not be what you need.

Hope it helps.

function getMatchIndices(r, str) {
  const indices = [];
  str.split('').forEach((v,i) => {
    if(r === str.substring(i,i+r.length)) {
      indices.push(i);
    }
  });
  return indices;
}

const line = "aabaabbaababaababaaabaabaaabaabbabaababa";
const rule = 'aba';

const indices = getMatchIndices(rule, line);

console.log(indices);
Bibberty
  • 4,670
  • 2
  • 8
  • 23