1

I have this string :

const test = `
/**
 * @test
 * {
 * }
 * @example
 * {
 *    "name": "Error",
 * }
 * @test
 * {
 * }
 * @example
 * {
 *    "name": "Success",
 * }
 */
`;

And i would like to return all the @example found in the string. Here is my code :

const regexExample = /@example[\s\S]*?(?=@test|$)/g;
let m;
do {
  m = regexExample.exec(test)
  if (m) {
    console.log(m[0]);
    return m[0];
  }
} while (m);

The output i get is :

@example
 * {
 *    "name": "Error",
 * }
 * 

How can i search for all the @example, and if an @ is found to verify if it's equivelant to @example

brxnzaz
  • 481
  • 1
  • 4
  • 15

1 Answers1

1

Your regex is good, just use it with String.prototype.match() to get all matches in one go:

const test = `
/**
 * @test
 * {
 * }
 * @example
 * {
 *    "name": "Error",
 * }
 * @test
 * {
 * }
 * @example
 * {
 *    "name": "Success",
 * }
 */
`;

const matches = test.match(/@example[\s\S]*?(?=@test|$)/g);

matches.forEach(m => console.log(m));
jo_va
  • 13,504
  • 3
  • 23
  • 47