Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-factoring regular expression to not include empty groups

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?

like image 642
Otis Wright Avatar asked May 27 '26 21:05

Otis Wright


1 Answers

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
like image 97
Laurel Avatar answered May 30 '26 10:05

Laurel