Hey so I have the following script which works:
It looks for the string Phone: (##) ### ####
$(function(){
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>");
target.html(string);
});
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 ($1, $2, $4) in this case.
So I can just use $1, $2, $3 in an ideal world.
Also I could not figure out how to stop (^|\W) from ignoring the > symbol, hence why in my replace 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
As Alan Moore said, you can also shorten it a bit:
/\bPhone:\s*\(?(?:[0-9]{2})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/g
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With