JavaScript – Find all Matches of a Regular Expression in a String

To find find all the matches of a regular expression in this string in JavaScript, call match() method on this string, and pass the regular expression as argument.

match() method returns an array of strings containing all the matches found for the given regular expression, in this string.

Syntax

The syntax to find all the matches for regular expression regex in the string str is

str.match(regex)
ADVERTISEMENT

Examples

The following is a quick example to find all the matches for regular expression regex in the string str in JavaScript.

var str = 'Hello World. Welcome to JavaScript.';
var regex = /[A-Za-z]+/g;
var result = str.match(regex); //returns array

In the following example, we take a string str and match all the words containing alphabets.

index.html

Now, let us take a regular expression that matches with the words that start with the letter W.

index.html

Conclusion

In this JavaScript Tutorial, we learned how to find all the matches for a regular expression in a string in JavaScript, using match() method, with examples.