Skip to content

JavaScript find all matches in string | Example code

  • by

Use the match() method to find all matches in string in JavaScript. You have to pass the regular expression as an argument in the method.

str.match(regex)

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

JavaScript find all matches in string

Simple example code finds all the matches for a regular expression regex in the string in JavaScript. Let’s get all the words containing alphabets.

<!DOCTYPE html>
<html>
<body>
  <script>
   var str = 'Hello World. Welcome to JavaScript.';

   var regex = /[A-Za-z]+/g;
   var res = str.match(regex);

   console.log(res)
 </script>
</body>
</html>

Output:

JavaScript find all matches in string

Matches with the words that start with the letter W.

<script>
    var str = 'Hello World. Welcome to JavaScript.';
    var regex = /W[A-Za-z]+/g;
    var res = str.match(regex);

    console.log(res)
</script>

Output: [ “World”, “Welcome” ]

Do comment if you have any doubts or suggestions on this Js string topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading