Parts of matched strings be “captured” for later use using group parentheses ()
. Captured groups allows you to pull out patterns from within the matched pattern and rearrange then as needed.
The index numbers for captured expressions begin to be numbered at 1 (i.e. $1, $2, $3, etc).
Greeting Example
let introduce = "Hello, my name is Joel.";
introduce.replace(/my\sname\sis\s(\w+)\./, "$1!");
> "Hello, Joel!"
Reverse Order
let string = 'abc';
string.replace(/(\w)(\w)(\w)/, "$3$2$1");
> "cba"
Decimal Pricing
let string = '5337';
string.replace(/(\d*)(\d{2})/, "$$$1.$2");
> '$53.37'
Note: Use two dollar signs $$
to print one dollar sign $.
Telephone Number
function reformatTelephone(telephone) {
return telephone.replace(/^(\d{3})(\d{3})(\d{4})$/, "($1) $2-$3");
}
reformatTelephone("5366081470");
> "(536) 608-1470"
Make it match more inputs:
function reformatTelephone(telephone) {
const regex = /^\D*(\d{3})\D*(\d{3})\D*(\d{4})\D*$/;
return telephone.replace(regex, "($1) $2-$3");
}
reformatTelephone("1234567890");
reformatTelephone("(123) 456-7890");
reformatTelephone("(123) 456-7890");
reformatTelephone("( 123 ) 456 - 7890");
> "(123) 456-7890"