Alessandro Lacava

on Designing and Developing Software. In love with Functional Programming.

Capturing Groups Using Regular Expressions (RegEx) In JavaScript

There are whole books about regular expressions so this post shouldn’t be intended as an exhaustive resource on the subject. It just shows how to extract a substring from a string using regular expressions in JavaScript so it must be considered just a tip not a tutorial on RegEx. Look at the following example:

1
2
3
4
5
6
7
8
9
10
var str = "http://www.alessandrolacava.com/?code=ALE69";
var regex = /code=(w+)&?/;
var results = regex.exec(str);
if(!results){
  alert("no match");
}
else{
  // first group
  alert(results[1]);
}

The previous code extracts the string that follows the code= part of str. That string is captured in the first group. of the RegEx, that’s why I use results[1] to display it. When you utilise groups–through the use of parenthesis ()–you can refer to them using indices, starting from 1. Indeed, at the index 0 you find the whole match. In the previous example, results[0] is equal to code=ALE69

Comments