Using .replace () with a conditional group

I have a regex (shown below) that works exactly how I would like it to work, except that I would like to insert an 'x'

if group $7

.

Is there a way to do this using .replace()

?

phoneNumber.replace(/(\()?(\d{3})(\))? ?(\d{3})-?(\d{4})( +)?(\d+)?/, '($2) $4-$5 x$7');

Input example: 7777777777

Sample input output: (777) 777-7777 x

Update:

Thanks @Amit Joki for the callback.

In the end this was what I used:

Note. The regex needed to be updated to include the one x

inserted by the callback.

phoneNumber.replace(/(\()?(\d{3})(\))? ?(\d{3})-?(\d{4})([ x]+)?(\d+)?/, 
    function(m, g1, g2, g3, g4, g5, g6, g7) {
        return "(" + g2 + ")" + " " + g4 + "-" + g5 + (g7 ? " x" + g7 : "");
    }
);

      

+3


source to share


1 answer


Yes, you can use a callback for that.

phoneNumber = phoneNumber.replace(/(\()?(\d{3})(\))? ?(\d{3})-?(\d{4})( +)?(\d+)?/, 
function(m, g1, g2, g3, g4, g5,g6,g7) { // matches
    return "(" + g2 + ")" + g4 + "-" + g5 + (g7 ? "x" : "");
});

      



Conditional part g7 ? "x" : ""

, which is a ternary operator that returns "x"

if g7

there is else empty string""

Learn more about the callback function on MDN

+3


source







All Articles