javascript - Regex to replace non-numeric characters and insert dashes for phone number as it is typed -


i need javascript format telephone number typed. replace non-numeric characters , insert dashes if user doesn't type them in. far closest i've gotten, thrown off if put dash in wrong spot. ideal solution replace dashes in wrong spots. looking way possibly replace 4th , 8th digit differently haven't come solution.

$('#telephoneno').keyup(function (ev) {         if (/[^0-9\-]/g.test(this.value))         {             this.value = this.value.replace(/[^0-9\-]/g, '');         }          if (/^(\d{3})(\d)/.test(this.value))         {             this.value = this.value.replace(/^(\d{3})(\d)/, '$1-$2');         }          if (/^(\d{3}-\d{3})(\d)/.test(this.value))         {             this.value = this.value.replace(/^(\d{3}-\d{3})(\d)/, '$1-$2');         }     }); 

assuming want format "123-456-7890":

function formatphonenumber(s) {   var s2 = (""+s).replace(/\d/g, '');   var m = s2.match(/^(\d{3})(\d{3})(\d{4})$/);   return (!m) ? null : m[1] + " -" + m[2] + "-" + m[3]; } 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -