how to match and extract a regex from text in javascript

To match and extract a regex from text in JavaScript, you can use the match() method or the exec() method of the RegExp object.

match() method returns an array of results. You can use it to return all matches in a string.

Example:

index.tsx
const text = "The quick brown fox jumps over the lazy dog";
const regex = /brown/;
const found = text.match(regex);
console.log(found); // ["brown"]
149 chars
5 lines

exec() method returns an array of matches, and also stores the index of the last match.

Example:

index.tsx
const text = "The quick brown fox jumps over the lazy dog";
const regex = /brown/;
let found;
while (found = regex.exec(text)) {
  console.log(`Found ${found[0]} at index ${found.index}`);
}
191 chars
7 lines

Output:

index.tsx
Found brown at index 10
24 chars
2 lines

Both methods can also return matched groups when capturing groups are used in the regex.

Example:

index.tsx
const text = "My phone number is (123) 456-7890";
const regex = /\((\d{3})\)\s(\d{3})-(\d{4})/;
const found = text.match(regex);
console.log(found); // ["(123) 456-7890", "123", "456", "7890"]
193 chars
5 lines

In the above example, found[0] is the entire matched string, found[1], found[2], and found[3] are the matched groups.

related categories

gistlibby LogSnag