Groups

Introduction

Parentheses group items together into a sub-expression.

Form

Characters may be grouped together to create clauses, which may be nested. Apart from grouping characters, parenthesis also serve to capture the desired sub-pattern within a pattern.

(. . .)

The values of the sub-patterns can be retrieved by using RegExp.$1, RegExp.$2, . . ., RegExp.$99 after the pattern itself is matched or compared.

RegExp.$1

Use

Example

var pattern = /(ab)*/; var string = "ababababababababababababababababababababababababababababab"; document.writeln("string.match(pattern) " + string.match(pattern)); document.writeln("string.match(pattern)[0] " + string.match(pattern)[0]); document.writeln("string.match(pattern)[1] " + string.match(pattern)[1]); document.writeln("string.match(pattern)[2] " + string.match(pattern)[2]); document.writeln("string.match(pattern)[3] " + string.match(pattern)[3]); document.writeln("RegExp.$0 " + RegExp.$0); document.writeln("RegExp.$1 " + RegExp.$1); document.writeln("RegExp.$2 " + RegExp.$2); document.writeln("RegExp.$3 " + RegExp.$3);

On running the above code, the following output is obtained.

The sub-expressions recognised above can be replaced by other text.

Example

var pattern = new RegExp("(a)(b)(c)"); var string = "abc"; document.writeln(string.replace(pattern, "$1-$2-$3"));

On running the above code, the following output is obtained.

Example

var pattern = /(\d+)-(\d+)-([a-z]+)/; var string = "123-234-abc"; document.writeln(string.replace(pattern, "$3 : $1-$2"));

On running the above code, the following output is obtained.

Example

var pattern = /(\w*)\s*(\w)\s*(\w*)/; var string = "Miss A Smith"; document.writeln(string.replace(pattern, "Dear $1 $3"));

On running the above code, the following output is obtained.

Example

var string="We read 2 chapters in 3 days"; var pattern=/(\d+) chapters/; string.match(pattern); document.writeln(RegExp.$1);

On running the above code, the following output is obtained.

Example

document.writeln("John Smith".replace(/(John) (Smith)/, "$2 $1"));

On running the above code, the following output is obtained.

Example

var pattern = /(abc)+(def)/; var string = "abcabcdef"; document.writeln(string.match(pattern));

On running the above code, the following output is obtained.