Skip to content Skip to sidebar Skip to footer

Stringify Match Result

How to show all matches content like for example [ 'JavaScript', index: 14, input: 'I am learning JavaScript not Java.', groups: undefined ] [

Solution 1:

String#prototype#matchAll returns an iterable, you need to typecast it to an array and reshape it to match your output like this -

const string = "I am learning JavaScript not Java.";
const re = /Java[a-z]*/gi;

let result = [...string.matchAll(re)].map((x) => ({
  match: x[0],
  index: x.index,
  input: x.input,
  groups: x.groups
}));

for (let match of result) {
  console.log(match);
}

Solution 2:

There is no way to represent an associative array in JSON. So, it removes all those properties from the array.

If you spread the associative array within {}, it will create an object with all those enumerable properties. This will still remove groups if you stringify because undefined isn't a valid value in JSON

const string = "I am learning JavaScript not Java.",
      re = /Java[a-z]*/gi,
      result = string.matchAll(re);

for (let match of result) {
  console.log({ ...match });
}

Shorter version:

const output = Array.from(result, match => ({ ...match }) )

Post a Comment for "Stringify Match Result"