Here is a combination of some of these answers. This can be used for input fields. Contains phone numbers 7 and 10 digits long.
// Used to format phone number function phoneFormatter() { $('.phone').on('input', function() { var number = $(this).val().replace(/[^\d]/g, '') if (number.length == 7) { number = number.replace(/(\d{3})(\d{4})/, "$1-$2"); } else if (number.length == 10) { number = number.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3"); } $(this).val(number) }); }
Real-time example: JSFiddle
I know that this does not directly answer the question, but when I was looking for the answers, this was one of the first pages I found. So, this answer is for those who are looking for something similar to what they were looking for.
Cruz Nunez May 31 '16 at 21:33 2016-05-31 21:33
source share