How to extract a string using JavaScript regex?

Sometimes, we want to extract a string using JavaScript regex.

In this article, we’ll look at how to extract a string using JavaScript regex.

How to extract a string using JavaScript regex?

To extract a string using JavaScript regex, we can use the regex exec method.

For instance, we write

const extractSummary = (iCalContent) => {
  const rx = /nSUMMARY:(.*)n/g;
  const arr = rx.exec(iCalContent);
  return arr[1];
};

to define the extractSummary function that gets the part of the iCalContent string that has the 'SUMMARY:' and some text after it.

Then we get the match with arr[1].

Conclusion

To extract a string using JavaScript regex, we can use the regex exec method.