Otis Wright Otis Wright - 5 months ago 9x
Javascript Question

Re-factoring regular expression to not include empty groups

Hey so I have the following script which works:

It looks for the string

Phone: (##) ### ####


var regex = /(^|\W)Phone:($|\W)\(?([0-9]{2})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/g;
var target = $('[data-hook="phone-number"]');
var string = target.html();

string = string.replace(regex, "><a href=\"tel:$3$5$6\">Phone: ($3) $5 $6</a>");


But as you may notice it is pretty rough (regex is not my strong point) I was wondering is there a way to ignore empty groups (
) in this case.

So I can just use
in an ideal world.

Also I could not figure out how to stop
from ignoring the
symbol, hence why in my
there is a trailing
is there a way to tell regex to shift / remove one number?


I think you are looking for (?:) which creates a non-capturing group:

/(?:^|\W)Phone:(?:$|\W)\(?(?:[0-9]{2})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/g