Search code examples
javascriptjqueryhtmlmasking

Phone masking function inserting extra "x's" in form field


My phone masking script is inserting the correct dashes but for numbers with extensions it is adding extra "x's" after the 12th character. I am trying to format the mask so it looks like 000-0000x0000000 but it is returning 000-000-0000xxxx0000. Any idea on what I am doing wrong?

$(document).ready(function() {	
	var phoneNumber = $('#phone_number');
	
	// Adds a phone number mask
  	phoneNumber.on('input paste', function(e) {
		var phoneNumStr = e.target.value.split("-").join("");

		// Create a new string with the hyphen
		pro = phoneNumStr.split('').map(function(str, index) {
		
			// Inserts a hyphen after the third and sixth characters
			if (index == 3 || index == 6) {
				return "-" + str;
			} else if (index == 10) {
				return "x" + str;
			} else {
				return str;
			}
		}).join('');
		
		// Returns the new string
		$(this).val(pro);
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="phone_number">Phone Number*</label> 
<input type="text" id="phone_number" name="phone_number" maxlength="20">


Solution

  • Changed your split '-' to use a regex to split on dash and x to remove the x's from the string that is evaluated.

    $(document).ready(function() {	
    	var phoneNumber = $('#phone_number');
    	
    	// Adds a phone number mask
      	phoneNumber.on('input paste', function(e) {
                                             //remove dash and x
    		var phoneNumStr = e.target.value.split(/[x-]/).join("");
    
    		// Create a new string with the hyphen
    		pro = phoneNumStr.split('').map(function(str, index) {
    		
    			// Inserts a hyphen after the third and sixth characters
    			if (index == 3 || index == 6) {
    				return "-" + str;
    			} else if (index == 10) {
    				return "x" + str;
    			} else {
    				return str;
    			}
    		}).join('');
    		
    		// Returns the new string
    		$(this).val(pro);
    	});
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <label for="phone_number">Phone Number*</label> 
    			<input type="text" id="phone_number" name="phone_number" maxlength="20">