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.tsx149 chars5 lines
exec()
method returns an array of matches, and also stores the index of the last match.
Example:
index.tsx191 chars7 lines
Output:
index.tsx24 chars2 lines
Both methods can also return matched groups when capturing groups are used in the regex.
Example:
index.tsx193 chars5 lines
In the above example, found[0]
is the entire matched string, found[1]
, found[2]
, and found[3]
are the matched groups.
gistlibby LogSnag