Otis Wright Otis Wright - 9 months ago 24
Javascript Question

Re factoring regular expression to not include empty variables

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 variables (
) 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