Skip to content

JavaScript regex match group | Example code

  • by

Using the JavaScript RegEx match group will help to find the multiple times. It is wasteful to repeat that regex manually. A better way to specify multiple repeated substrings is using the “RegEx Capturing Groups” in the match() method.

str.match(regex);

JavaScript regex match group

Simple example code searching in the string for patterns. Parentheses ( ), are used to find repeated substrings. We just need to put the regex that will repeat in between the parentheses.

<!DOCTYPE html>
<html>
<body>
  <script>
    let regex = /(go)+/ig;
    let str = 'goGoGOgOgoooogo';

    let result = str.match(regex);
    console.log(result); 
    
  </script>

</body>
</html>

Output:

JavaScript regex match group | Example code

Specify RegEx Capturing Groups using Numbers

let repeatNum = "93 93 93";
let wrongNum = "100 100 200 100";

let regex = /^(\d+)\s\1\s\1$/;

let result = regex.test(repeatNum);
console.log(result); //true

result = repeatNum.match(regex);
console.log(result); // [ '93 93 93' ]

let wrongRes = regex.test(wrongNum);
console.log(wrongRes); //false

wrongRes = wrongNum.match(regex);
console.log(wrongRes); //null

Output:

Specify RegEx Capturing Groups using Numbers

/^(\d+)\s\1\s\1$/ this regex explains:

  • A caret ( ^ ) is at the beginning of the entire regular expression, it matches the beginning of a line.
  • (\d+) is the first capturing group that finds any digit from 0-9 appears at least one or more times in the string?
  • \s finds a single white space
  • \1 represents the first capturing group which is (\d+).
  • A dollar sign ( $ ) is at the end of the entire regular expression, it matches the end of a line.

Capturing groups in replacement

Method str.replace(regexp, replacement) that replaces all matches with regexp in str allows using of parentheses contents in the replacement string. That’s done using $n, where n is the group number.

let str = "John Bull";
let regexp = /(\w+) (\w+)/;

alert( str.replace(regexp, '$2, $1') ); // Bull, John

Do comment if you have any doubts or suggestions on this JS match 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

Your email address will not be published. Required fields are marked *