Substring Regex in Javascript

In JavaScript, regular expressions can be used with the substring() method to extract substrings based on specific patterns. Here’s an example of using regular expressions with substring():

javascriptCopy codevar str = "Hello, World!";
var pattern = /Hello/g;
var matches = str.match(pattern);

if (matches) {
  var substring = str.substring(matches.index, matches.index + matches[0].length);
  console.log(substring); // Output: Hello
} else {
  console.log("No match found.");

In this example, we define a regular expression pattern /Hello/g to match the substring “Hello” in a case-sensitive manner. The g flag indicates a global search to find all occurrences of the pattern.

We then use the match() method on the str string to search for matches based on the regular expression. If a match is found, the result is stored in the matches variable, which is an array.

We can then use the substring() method to extract the first match from the str string. The matches.index property gives the starting index of the first match, and matches[0].length gives the length of the matched substring. By passing these values to substring(), we extract the substring “Hello”.

If no match is found, the match() method returns null, and the “No match found.” message is printed.

You can modify the regular expression pattern to match different substrings or use more complex patterns based on your specific requirements. Regular expressions provide a flexible way to define search patterns and extract substrings in JavaScript.