How to return all matching strings against a RegEx in JavaScript?

In this blog we will learn how to identify if a string matches with a regular expression and subsequently return all the matching strings in JavaScript. We can use JavaScript’s string.search() method. This method searches for a match between a regular expression in a given string.

Syntax:

let index = string.search(expression)

Parameters used:

  • String − This is the string that will be searched in comparison with the regular expression.
  • Expression − This is the regular expression and the conditions that will be used for validating the original string. It will check if the substring is present in the original string.

Table of Contents

Example 1

Code:

<!DOCTYPE html>
<html>
<head>
   <title>
      Comparing Strings
   </title>
</head>
<body>

   <h2 style="color:green">
      Welcome To CodingIsEasy 
   </h2>
</body>
   <script>

      // Taking a String input.
      var string = "Start Learning new technologies now.";

      // Defining a regular expression
      var regexp1 = /Lea/;
      var regexp2 = /rn/;
      var regexp3 = /abc/;
      console.log("Matched at:"+string.search(regexp1));

      // Expected Output: 6
      console.log("Matched at:"+string.search(regexp2));

      // Expected Output: 9
      console.log("Matched at:"+string.search(regexp3));

      // Expected Output: -1
   </script>
</html>

In the above example, we compared a string with a substring/regular expression that is rendered in the function. This method will return only the elements that match the expression, otherwise the string will not be returned.

Example 2

Code:

<script>

	// Taking an array of strings.
	let strings = [
		"CodingIsEasy is a web development's portal",
		"It's one of the best platform for web developers",
		"I am developer",
		"I am a student",
		"I am a computer science Geek"
	];

	let i;
	
	// Taking a regular expression
	let regexp = /dev/;
	let arr = [];

	for (i = 0; i < strings.length; i++) {
		if (strings[i].search(regexp) != -1) {
			arr.push(strings[i])
		}
	}
	console.log(arr)
</script>

Output:

[
  "CodingIsEasy is a web development's portal",
  "It's one of the best platform for web developers",
  'I am developer'
]

That’s it for this tutorial. Hope it was helpful for you.

Leave a Comment