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)
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<h3>All Matchings</h3>
<pre id="output"></pre>
<script>
var str = 'Hello World. Welcome to JavaScript.';
var regex = /[A-Za-z]+/g;
var result = str.match(regex);
//print all the matches found in the string
result.forEach(function printing(element, index) {
document.getElementById('output').append(element + '\n');
})
</script>
</body>
</html>
Now, let us take a regular expression that matches with the words that start with the letter W
.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<h3>All Matchings</h3>
<pre id="output"></pre>
<script>
var str = 'Hello World. Welcome to JavaScript.';
var regex = /W[A-Za-z]+/g;
var result = str.match(regex);
//print all the matches found in the string
result.forEach(function printing(element, index) {
document.getElementById('output').append(element + '\n');
})
</script>
</body>
</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.