Substring Match() Method In Javascript

If you want to find all substring matches within a string in JavaScript, you can use regular expressions along with the match() method. Here’s an example:

var str = "Hello, Hello, Hello!";
var substring = "Hello";
var regex = new RegExp(substring, "g");
var matches = str.match(regex);

console.log(matches); // Output: ["Hello", "Hello", "Hello"]

In this example, we use the match() method along with a regular expression to find all occurrences of the substring within the str string. The regular expression new RegExp(substring, "g") is created with the “g” flag, which indicates a global search to find all matches.

The match() method returns an array containing all the matches found. In this case, since “Hello” appears three times in the string, the output is ["Hello", "Hello", "Hello"].

Note that the match() method returns null if no matches are found. To handle this case, you can add a conditional check like:

if (matches) {
  console.log(matches);
} else {
  console.log("No matches found.");
}

This will print the matches if they exist or display a message if no matches are found.

You can also use regular expression literals instead of creating a RegExp object, like this:

var str = "Hello, Hello, Hello!";
var substring = "Hello";
var regex = /Hello/g;
var matches = str.match(regex);

console.log(matches); // Output: ["Hello", "Hello", "Hello"]

In this case, the regular expression /Hello/g is used directly without using the RegExp constructor. The rest of the code remains the same.

Regular expressions provide powerful pattern matching capabilities, allowing you to search for more complex patterns within a string. You can modify the regular expression pattern to match different substrings based on your requirements.