In JavaScript regular expressions, parentheses can be used to:
1. Group items together
2. Refer to an previous sub-expression within an expression
These are explained below:
1. In JavaScript, parentheses can be used in regular expressions to group items together. Consider this example:
([._][a-z])+
The preceding pattern will match a period or underscore [._], followed by a lowercase letter character [a-z], matching 1 or more occurrences (+).
2. Another use of parentheses in JavaScript is to refer to a previous sub-expression within an expression.
As parentheses are added in an expression, JavaScript keeps track of them by number, with the left-most parentheses being number 1. In the expression /^([ab](c)?)+$/, JavaScript is aware that the parentheses containing [ab](c)? is 1 and the parentheses containing c is 2. To refer to these positions, precede the position digit with a backslash, such as \1. These positions can also be referred to in a replace operation by preceding them with a $.
var TestString = “javascript”;
alert(TestString.replace(/java(.*)/,’action$1′));
This example replaces ‘java’ with ‘action’ and then takes anything that was after ‘java’ in the test string and appends it to the replace string. So the result is ‘actionscript.’
Another example comes from the Mozilla Developer Center:
re = /(\w+)\s(\w+)/;
str = “John Smith”;
newstr = str.replace(re, “$2, $1″);
alert(newstr);
The result of this is Smith, John.
External References:
Mozilla Developer Center