Categories
JavaScript Answers

How to extract a string using JavaScript regex?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *