1

I have following working code.

indexMatches = [];
function getMatchIndexes(str, toMatch) {
    var toMatchLength = toMatch.length,
        match,
        i = 0;

    while ((match = str.indexOf(toMatch, i)) > -1) {
        indexMatches.push(toMatch);
        i = match + toMatchLength;
    }
    return indexMatches;
}

console.log(getMatchIndexes("this is code [table which has [table table [row and rows [table]", "[table"));

Fiddle here: https://jsfiddle.net/vqqq1wj4/

However I have to match 2 string to search [table and [row and add to indexes. Currently it accepts only 1 parameter to search. I tried adding the same with OR operator in while but it doesnt work. Ideally I should write the following code

getMatchIndexes(str, "[table","[row");

and it would return the array below according to their index and positions properly.

 [ "[table", "[table", "[row", "[table" ]
Themer
  • 185
  • 1
  • 12

1 Answers1

3

Use String#match with regex which is generated using the string.

function getMatchIndexes(str, ...toMatch) {
  return str.match(
    // generate regex
    new RegExp(
      // iterate over strings
      toMatch.map(function(v) {
        // escape symbols which has special meaning in regex
        return v.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
      // join with pipe operator and specify g for global match
      }).join('|'), 'g'));
}

console.log(getMatchIndexes("this is code [table which has [table table [row and rows [table]", "[table", "[row"));

Refer : Converting user input string to regular expression

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • Just for refernce, what does ... means ? – Themer Dec 28 '16 at 19:17
  • 1
    @Themer : which is [spread operator](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator).. or pass the values as an array...... i.e, `console.log(getMatchIndexes("this is code [table which has [table table [row and rows [table]", ["[table", "[row"]]));` & `function getMatchIndexes(str, toMatch){....` – Pranav C Balan Dec 28 '16 at 19:18
  • ok thanks. one last thing, if it now much as I never understand regex code. What if I search getMatchIndexes("this is code [table which has [table table [row and rows [table]", ["table", "row"]]); without [ bracket and it should ignore the word table but only count [table and return the same output.. – Themer Dec 28 '16 at 19:25
  • @Themer : that would match `table`.... o/p => `[ "table", "table", "row", "table" ]` – Pranav C Balan Dec 28 '16 at 19:26